Where can I access getContext()
in a Fragment
? I mean, it is not null and can be used (for instance, for controls creation). Is it onAttach
, onCreateView
or onActivityCreated
?
All the mentioned answers are basically correct. You should get the activity's context between onAttach and onDetach so I like adding this to my fragments:
private Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
@Override
public void onDetach() {
super.onDetach();
mContext = null;
}
and then whenever I use mContext I add a check:
if(mContext != null) {
//your code that uses Context
}
UPDATE:
In Support Library 27.1.0 and later, Google has introduced new methods requireContext() and requireActivity() that will return a non null Context or Activty.
If the Fragment is not currently attached at the time of calling the method, it will throw an IllegalStateException: so use within a try catch block.
getContext()
will always be not null between onAttach()
and onDetach()
Use getActivity()
between onAttach
and onDetach
to get the attached Activity
which is the Context
of the Fragment
.
You're pretty safe by calling getContext()
inside onCreateView()
. If you take a look at the docs you'll see that from onAttach
onwards your fragment will have a context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With