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.
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:
WeakReference
is used and checked for null
before use in order to allow the referred-to item to get garbage-collectedThe 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.