How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?

Database constructor

public Database(Context ctx){this.context=ctx;DBHelper=new DatabaseHelper(context);}

    24 Answers24

    up vote1179down voteaccepted

    You can use getActivity(), which returns the activity associated with a fragment.
    The activity is a context (since Activity extends Context).

    • 190
      getActivity() can return null if it is called before onAttach of the respective fragment.– arne.jansApr 29 '13 at 15:36
    • 3
      I was reading this Google blog on memory leaks...android-developers.blogspot.com/2009/01/… . If I use the getActivity() method would the app not be at risk of memory leaks? The blog suggests "Try using the context-application instead of a context-activity" which isn't really possible as getApplicationContext() only works for the Activity class and not the Fragment class.– SimonApr 6 '14 at 17:40
    • 35
      A solution for the problem of detached fragments is to store the value of getActivity().getApplicationContext() in an instance variable when the fragment is created and then use that context whenever you want inside the fragment class. That context will survive fragment detachments.– PiovezanJun 11 '14 at 15:08
    • 7
      Instead of passing around the application context, create a static context inside your Application class and initialize it onCreate(): MyApplication.sContext=getApplicationContext(); then you can access it from any activity/fragment without worrying about detachment.– Eduard KotyshFeb 23 '15 at 18:18
    • 2
      @milaniez: getActivity has always been available. It's getContext which was added in API 23.– mhsmithSep 15 '17 at 12:10

    To do as the answer above, you can override the onAttach method of fragment:

    public static class DummySectionFragment extends Fragment{...@Overridepublic void onAttach(Activity activity) {super.onAttach(activity);DBHelper=new DatabaseHelper(activity);}}
    • 3
      I would recommend this, as getActivity() returns null if onAttach isn't called yet.– arne.jansApr 29 '13 at 15:36
    • 6
      But, keep in mind, when onAttach() is called, there are no views. So you cannot do anything with views yet!– ZordidJun 3 '13 at 19:30
    • 2
      @iambox what if DatabaseHelper needed a FragmentActivity instead of an Activity? For example, for an Adapter...– JagoJun 19 '13 at 11:27
    • 4
      If you store a reference to your activity in onAttach(Activity activity) then you should release it in onDetach()– vovahostNov 14 '14 at 19:56
    • 3
      The onAttach method has been deprecated, Overrides deprecated method in 'android.support.v4.app.Fragment'– Muhammad SaqibMay 5 '17 at 17:26

    Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity().

    • 11
      I would not say that fragments are "slightly unstable", it seems quite normal for getActivity() to return null when the fragment does not belong to an activity. It is assuming that getActivity() "should not return null" (which is wrong) that would make your app (and not the Fragment class) unstable.– personne3000Apr 13 '14 at 2:31
    • 2
      @personne3000 I'd like to hear more. When is a fragment not belonging to an Activity? When is this happening and why? Should we be checking isAdded() in the fragment in order to use getActivity()? Any rule of thumb?– SottiApr 22 '15 at 15:41
    • 1
      @Sotti I encourage you to create a new question for this (or look for an existing one), since this specific subject is a little different from the original question. You can have a look at developer.android.com/guide/components/fragments.html#Lifecycle for general information. Basically, before onAttach and after onDetach, no activity. And between onAttach and onActivityCreated, the activity's onCreate has not been called yet. When using getActivity(), make sure your activity was already created, and think about what would happen if it was destroyed or your fragment was detached.– personne3000Apr 22 '15 at 23:44

    The easiest and most precise way to get the context of the fragment that I found is to get it directly from the ViewGroup when you call onCreateView method at least here you are sure not to get null for getActivity():

    public class Animal extends Fragment { Context thiscontext;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){thiscontext=container.getContext();
    • 10
      that's the context of the container, I think ... not "this context".– FattieMay 27 '14 at 12:38
    • This code made my code crash... avoid.– AG1Jan 24 '15 at 8:42
    • 2
      @AG1 could you please explain why did it crashed your code? This is so far the best solution I've got– MachadoJun 24 '15 at 14:55
    • 3
      Actually on dialogFragments the container can be null. Be carefull!– Lucas TeskeAug 7 '15 at 1:42
    @Overridepublic void onAttach(Activity activity) {// TODO Auto-generated method stubsuper.onAttach(activity);context=activity;}

      to get the context inside the Fragment will be possible using getActivity() :

      public Database(){this.context=getActivity();DBHelper=new DatabaseHelper(this.context);}
      • Be careful, to get the Activity associated with the fragment using getActivity(), you can use it but is not recommended it will cause memory leaks.

      I think a better aproach must be getting the Activity from the onAttach() method:

      @Overridepublic void onAttach(Activity activity) {super.onAttach(activity);context=activity;}
      • You shouldnt be using getActivity in a fragment to get a view unless that view is part of the activity anyway. Why would you inflate a view in a fragment then not even reference anything from it?– tyczjDec 5 '14 at 22:53
      • This answer is about something different, you're talking about which view hiearchy to search for views in. Activity.findViewById is just a convenience method to search for a view in that activity's registered content view (set through setContentView). In your correct example you are calling View.findViewById, not Activity.findViewById, and you are invoking the method on the correct root view. Totally different problem, and obviously you won't be able to find your view in a view hiearchy that doesn't hold that view.– JHHMar 2 '16 at 12:36
      • I have edited my answer.– JorgesysMar 2 '16 at 16:06

      Another alternative approach is:

      You can get the context using:

      getActivity().getApplicationContext();
      • @tyczj read fully to understand on your link– codercatApr 8 '14 at 8:57

      You could also get the context from the inflater parameter, when overriding onCreateView.

      public static class MyFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {/* ... */Context context=inflater.getContext();/* ... */}}

        getContext() came in API 23. Replace it with getActivity() everywhere in the code.

        See if it fixes the error. Try to use methods which are in between the target and minimun API level, else this error will come in place.

          Since API level 23 there is getContext() but if you want to support older versions you can use getActivity().getApplicationContext() while I still recommend using the support version of Fragment which is android.support.v4.app.Fragment.

            getActivity() is a child of Context so that should work for you

              Use fragments from Support Library -

              android.support.v4.app.Fragment

              and then override

              void onAttach (Context context) {this.context=context;}

              This way you can be sure that context will always be a non-null value.

                You have different options:

                • If your minSDK <=21, then you can use getActivity(), since this is a Context.
                • If your minSDK is >=23, then you can use getContext().

                If you don't need to support old versions then go with getContext().

                  For Kotlin you can use context directly in fragments. But in some cased you will find an error like

                  Type mismatch: inferred type is Context? but Context was expected

                  for that you can do this

                  val ctx=context ?: returntextViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))

                    Ideally, you should not need to use globals. The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment.

                    Then: you can dereference the fragment to get activity, context or applicationcontext as you desire:

                    this.getActivity() will give you the handle to the activitythis.getContext() will give you a handle to the contextthis.getActivity().getApplicationContext() will give you the handle to the application context. You should preferably use the application context when passing it on to the db.

                      The simple way is to use getActivity(). But I think the major confusion of using the getActivity() method to get the context here is a null pointer exception.

                      For this, first check with the isAdded() method which will determine whether it's added or not, and then we can use the getActivity() to get the context of Activity.

                      You can call getActivity() or,

                      public void onAttach(Context context) {super.onAttach(context);this.activity=(CashActivity) context;this.money=this.activity.money;}

                        getContext() method helps to use the Context of the class in a fragment activity.

                          I think you can use

                          public static class MyFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {Context context=getActivity.getContext();}}
                            public class MenuFragment extends Fragment implements View.OnClickListener {private Context mContext;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);View view=binding.getRoot();mContext=view.getContext();return view;}}

                              Also you can use:

                              inflater.getContext();

                              but I would prefer to use

                              getActivity()

                              or

                              getContext

                                I need context for using arrayAdapter IN fragment, when I was using getActivity error occurs but when i replace it with getContext it works for me

                                listView LV=getView().findViewById(R.id.listOFsensors);LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));

                                  You can use getActivity() or getContext in Fragment.

                                  Documentation

                                  /*** Return the {@link FragmentActivity} this fragment is currently associated with.* May return {@code null} if the fragment is associated with a {@link Context}* instead.** @see #requireActivity()*/@Nullablefinal public FragmentActivity getActivity() {return mHost==null ? null : (FragmentActivity) mHost.getActivity();}

                                  and

                                   /*** Return the {@link Context} this fragment is currently associated with.** @see #requireContext()*/@Nullablepublic Context getContext() {return mHost==null ? null : mHost.getContext();}

                                  Pro tip

                                  Check always if(getActivity!=null) because it can be null when fragment is not attached to activity. Sometimes doing long operation in fragment (like fetching data from rest api) takes some time. and if user navigate to another fragment. Then getActivity will be null. And you will get NPE if you did not handle it.

                                  • what is mHost???– busuuAug 18 at 17:54
                                  • This is an documentation of getActivity() method, just to show that these can be null. Here mHost is instance of FragmentHostCallback class.– KhemrajAug 19 at 4:14

                                  Previously I'm using onAttach (Activity activity) to get context in Fragment

                                  Problem

                                  The onAttach (Activity activity) method was deprecated in API level 23.

                                  Solution

                                  Now to get context in Fragment we can use onAttach (Context context)

                                  onAttach (Context context)

                                  • Called when a fragment is first attached to its context. onCreate(Bundle) will be called after this.

                                  Documentation

                                  /*** Called when a fragment is first attached to its context.* {@link #onCreate(Bundle)} will be called after this.*/@CallSuperpublic void onAttach(Context context) {mCalled=true;final Activity hostActivity=mHost==null ? null : mHost.getActivity();if (hostActivity !=null) {mCalled=false;onAttach(hostActivity);}}

                                  SAMPLE CODE

                                  public class FirstFragment extends Fragment {private Context mContext;public FirstFragment() {// Required empty public constructor}@Overridepublic void onAttach(Context context) {super.onAttach(context);mContext=context;}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View rooView=inflater.inflate(R.layout.fragment_first, container, false);Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();// Inflate the layout for this fragmentreturn rooView;}}

                                  NOTE

                                  We can also use getActivity() to get context in Fragmentsbut getActivity() can return null if the your fragment is not currently attached to a parent activity,

                                    protected by Pavneet_Singh Jul 27 at 18:43

                                    Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

                                    Would you like to answer one of these unanswered questions instead?

                                    Not the answer you're looking for? Browse other questions tagged or ask your own question.