OckhamsRazor OckhamsRazor - 1 year ago 50
Android Question

Inner classes: Android vs Java

I'm aware that inner classes are not recommended in Android because they hold a reference to the enclosing class. However, in Java, the outer class is only GCed when the inner class is no longer referenced. That means, in Android, provided you have a non-static reference in the outer activity class to the inner class, the inner class cannot exist longer than the outer activity class because the activity can only be destroyed if it doesn't hold a reference to the inner class anymore (at least that is what I'm inferring). So what's the problem using non-static inner classes then (since they can't obviously exist longer than the outer activity if you infer from java)? Am I missing something?


Answer Source

Consider this simple example

class Leaker 
    public static Object leakedObj;

class MyActivity extends Activity
     public class MyInnerClass { ... }

     void onCreate(Bundle savedState) 
        Leaker.leakedObj = new MyInnerClass();
        //The activity now won't be GCed until Leaker.leakedObj is cleared.          

You can easily pass an inner non-static class outside the context of your activity. As long as you don't pass your inner class to objects outside of your Activity's lifecycle you should be okay. But it certainly IS possible to leak your activity via an inner class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download