Interview - Android Code
I was in an interview, what should be wrong with the next one?
I can assume the problem is that you cannot check if the class is null ?! Thank!
public class NiceActivity extends Activity {
private static AmazingClass a;
class AmazingClass {
int x;
int y;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nice);
if (a == null) {
a = new AmazingClass();
}
}
}
source to share
The inner class is not static, which can cause it to animate an activity that still has a reference to it. This can lead to leakage of activity.
This article explains this issue in more detail: http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html
source to share
Since the inner AmazingClass is not static, each instance has an implicit reference to the outer class (NiceActivity).
NiceActivity has a link to AmazingClass and this link is never cleared.
Hence, the activity will never be garbage collected and memory leaked.
In the diagram, it will look something like this:
root GC -1-> Activity class -2-> Amazing object -3-> Activity object
You need to clean up the reference number 2 or 3 to avoid such a leak.
source to share