Last active
October 31, 2019 21:37
-
-
Save anitaa1990/0afdf7e7246b366aa80e9bd59698c392 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; | |
*/ | |
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