Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anitaa1990/7afbf36d4856168bd6855aea2367e0a4 to your computer and use it in GitHub Desktop.
Save anitaa1990/7afbf36d4856168bd6855aea2367e0a4 to your computer and use it in GitHub Desktop.
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));
}
}
}
}
@zmer007
Copy link

zmer007 commented Jul 19, 2019

Line 40 should be this.messageViewReference = new WeakReference<>(activity), I guess.

@control-man
Copy link

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