Search code examples
androidandroid-activityandroid-context

When should we call getContext and getActivity once and for all?


I searched a lot on StackOverflow and more generally on Google for explanations about the use of contexts in the Android environment, but I only found scattered fragments of explanations.

When should we use getContext instead of getActivity? The question is precised below.

  • Within a DialogFragment, and other Fragment: creating a Toast, building an AlertDialog,instanciating an Intent... require a context. Should we use getActivity or getContext?
  • And if these operations are written in an Activity instead of a fragment?

By the way, a Null exception and/or memory leaks can occur by calling getContext and getActivity: when? More precisely: does it occur only when the lifetime of the caller is a (strict) subset of the lifetime of the called object (for example, a Dialog calls getActivity/getContext which returns null if it's not yet attached to its activity)?


Solution

  • From the DOCS, The Context object contains global information about an application environment. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

    the getContext() method returns the context associated with the current object, which may be a View, or a Fragment or Dialog or any other object that has this method defined in it or inherits it.

    the getActivity() method returns a reference to the current activity associated with a Fragment object. If there is no activity associated with the fragment it WILL return null. I personally never use this method when passing a context argument, I only use getContext() and getApplicationContext().

    getApplicationContext() is especially useful because it uses a Context whose lifecycle is separate from the current context, it is tied to the lifetime of the process rather than the current component. Which means it uses the context of the App instead of that of part of the app, like an activity. see here

    Context Best Practices:

    • getContext() and getApplicationContext() are sufficient for passing a context argument. If they are not accessible immediately you can use getActivity().getApplicationContext() chaining to pass appropriate context argument. This means you can use this to create Toasts, AlertDialogs, Intents, Fragments and other view manipulations that require context.
    • Never assign a context to a static (class) variable, It will create a memory leak!
    • If you use getApplicationContext() to register broadcasts you must perform the appropriate clean-up to prevent memory leaks. see here

    Note that these are my personal approaches, I stand to be corrected :).