Skip to content

Instantly share code, notes, and snippets.

@anitaa1990
Last active October 31, 2019 21:37
Show Gist options
  • Save anitaa1990/0afdf7e7246b366aa80e9bd59698c392 to your computer and use it in GitHub Desktop.
Save anitaa1990/0afdf7e7246b366aa80e9bd59698c392 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;
*/
private static 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();
}
/*
* Mistake Number 2:
* 1. Never create a inner variable of an inner class
* 2. Never pass an instance of the activity to the inner class
*/
private class LeakyClass {
private Activity activity;
public LeakyClass(Activity activity) {
this.activity = activity;
}
public void redirectToSecondScreen() {
this.activity.startActivity(new Intent(activity, SecondActivity.class));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment