Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getContext() in Fragment

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?

like image 465
CoolMind Avatar asked Feb 08 '18 14:02

CoolMind


4 Answers

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.

like image 117
Mr.O Avatar answered Oct 19 '22 23:10

Mr.O


getContext() will always be not null between onAttach() and onDetach()

like image 43
Alexander Deych Avatar answered Oct 20 '22 00:10

Alexander Deych


Use getActivity() between onAttach and onDetach to get the attached Activity which is the Context of the Fragment.

like image 2
Benjamin Avatar answered Oct 19 '22 22:10

Benjamin


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.

like image 1
Levi Moreira Avatar answered Oct 19 '22 22:10

Levi Moreira