Skip to content Skip to sidebar Skip to footer

Do Listeners Create Memory Leaks If Not Removed From A Destroyed Activity?

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. D

Solution 1:

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

classMyKitchenSinkimplementsRunnable, KeyListener, ....

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.

Solution 2:

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...

Post a Comment for "Do Listeners Create Memory Leaks If Not Removed From A Destroyed Activity?"