Sunday, May 22, 2011

Avoiding Memory Leaks : Android Program

Avoid Memory leaks in Android Program.


* Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)

At the onset of learning customizing lists its tempting to do this mistake. We just pass reference of the present context to the adapater.
Now the problem arises when we use our programming skills to release the activity and its resources on OnDestroy callback, while activity gets destroyed but remember reference to the this activity context is still referenced by our list. And this leaks the Context means it can't be reclaimed by Garbage collector.

* Try using the context-application instead of a context-activity
Context.getApplicationContext() and use it in the application.

* Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance


* A garbage collector is not an insurance against memory leaks