Search code examples
androidandroid-activityandroid-contextandroid-memory

Android: Memory leaks because of activity and context stored as objects attributes?


Is there any risk to raise a "Memory leaks" exception (e.g.) if we create an object attribute activity and another one context, defined in the onAttach() method?

It can be useful, especially for context in a dialog class.


Solution

  • Given the reference to #onAttach(), it sounds like you're dealing with fragments. As per Android documentation:

    the fragment can access the FragmentActivity instance with getActivity() and easily perform tasks such as find a view in the activity layout

    The APIs are designed to expose any needed Context to you so it's more idiomatic to simply use getActivity() where/when necessary.

    In general if you take a reference to any UI element, or any type of Context you must make sure that either:

    1. The lifetime of where you're holding a reference is contained completely within the lifetype of the thing being referred to
    2. OR ... a WeakReference is used and checked for null before use in order to allow the referred-to item to get garbage-collected

    The lifecycle of UI elements are strictly contained within the enclosing Context, so it is normal for them to directly reference the context without use of a WeakReference.

    Furthermore, there are explicit examples of relying on the parent context outliving the fragment specifically for dialogs.