What is different between getContext and getActivity from Fragment in support library?

What is different between getContext() and getActivity() from Fragment in support library?

Do they always return the same object? (activity associated with current fragment)


Solution 1:

In most cases there is no difference but ...

So originally Fragments were hosted in FragmentsActivity and back then to get Context one called getActivity().

Just checked the sources and Fragments now can be hosted by anyone implementing FragmentHostCallback interface. And this changed in Support Library version 23, I think.

When using newer version of Support Library, when Fragment is not hosted by an Activity you can get different objects when calling getActivity() and getContext().

When you call getActivity() you get an Activity which is a Context as well. But when you call getContext you will get a Context which might not be an Activity.

Solution 2:

So far, the only provided implementation of FragmentHostCallback (in the OS and the support library) always returns the same value for both getContext() and getActivity().

However, the other constructors of FragmentHostCallback suggest that in future implementations, we may get:

  • A null Activity and a non-null Context which is not an Activity. This looks improbable but we can imagine that fragments could be used outside Activities in the future, or be fully sandboxed.
  • A non-null Activity and a non-null Context which is not the same instance as the Activity. For example, Context could be a ContextThemeWrapper.

Conclusion: when you can, use getContext(). When you need Activity-specific calls, use getActivity().

Solution 3:

Activity is a subclass of Context. Activity has also Window elements and access to UI methods, Context doesn't. However, in the majority of the cases, it's the same if you need only the Context.

Solution 4:

getContext():- Returns the context the view is currently running in. Usually the currently active Activity. getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

getActivity():- This method gives the context of the Activity. You can use it is like the yourActivity.this. getActivity() is normally used in fragments to get the context of the activity in which they are inserted or inflated.