If you add a listener to a control/view and do not remove it, will that create a memory leak? For example, onCreate
adds a listener to an EditText
that listens for modifications. Do you need to remove this listener in the onDestroy?
I imagine that if you use an anonymous listener or a local variable that implements the listener, the memory would be free'd when the Activity
is destroyed due to scoping rules.
The only way I could see a memory leak potential is if the listener was passed in an intent object. Thoughts?
By themselves, listener do not create a memory leak. However, they're often used improperly and so may lead to leaks. Sometimes you see code where an object refers to a Component (e.g. for displaying messages there), which has a listener, which refers (possibly indirectly) to the first object. This forms a cycle and all its members live and die together. When the Component is a dialog which is meant to be short-living, you may have a problem. Beginners tend to use objects like
which may have a lot of references and makes it easier to build a memory leak*. Not creating "universal classes" is the way to go.
* It's no "real" memory leak like in
C
, since all the objects stays reachable and could be used if you wanted to. It's just keeping object reachable for a much longer time than expected, which eats you memory just like a leak.A memory leak should not be created unless something other than the control/view references the listener - no need to remove the listener in the onDestroy...