Created
May 16, 2018 16:10
-
-
Save anitaa1990/7afbf36d4856168bd6855aea2367e0a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InnerClassReferenceLeakActivity extends AppCompatActivity { | |
/* | |
* Mistake Number 1: | |
* Never create a static variable of an inner class | |
* Fix I: | |
*/ | |
private LeakyClass leakyClass; | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_first); | |
new LeakyClass(this).redirectToSecondScreen(); | |
/* | |
* Inner class is defined here | |
* */ | |
leakyClass = new LeakyClass(this); | |
leakyClass.redirectToSecondScreen(); | |
} | |
/* | |
* How to fix the above class: | |
* Fix memory leaks: | |
* Option 1: The class should be set to static | |
* Explanation: Instances of anonymous classes do not hold an implicit reference to their outer class | |
* when they are "static". | |
* | |
* Option 2: Use a weakReference of the textview or any view/activity for that matter | |
* Explanation: Weak References: Garbage collector can collect an object if only weak references | |
* are pointing towards it. | |
* */ | |
private static class LeakyClass { | |
private final WeakReference<Activity> messageViewReference; | |
public LeakyClass(Activity activity) { | |
this.activity = new WeakReference<>(activity); | |
} | |
public void redirectToSecondScreen() { | |
Activity activity = messageViewReference.get(); | |
if(activity != null) { | |
activity.startActivity(new Intent(activity, SecondActivity.class)); | |
} | |
} | |
} | |
} |
I also agree with line 40 would has a problem
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 40 should be
this.messageViewReference = new WeakReference<>(activity)
, I guess.