Using context in a fragment

581,039

Solution 1

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

public static class DummySectionFragment extends Fragment{
...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        DBHelper = new DatabaseHelper(activity);
    }
}

Solution 2

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;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();

Solution 3

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().

Solution 4

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.
 */
@CallSuper
public 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
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @Override
    public 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 fragment
        return rooView;
    }

}

NOTE

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

Solution 5

The correct way is to use

requireContext()

and the example

ContextCompat.getColor(requireContext(), R.color.colorAccent),
Share:
581,039
tyczj
Author by

tyczj

Updated on July 21, 2022

Comments

  • tyczj
    tyczj almost 2 years

    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);
    }
    
  • arne.jans
    arne.jans about 11 years
    I would recommend this, as getActivity() returns null if onAttach isn't called yet.
  • Zordid
    Zordid about 11 years
    But, keep in mind, when onAttach() is called, there are no views. So you cannot do anything with views yet!
  • Jago
    Jago about 11 years
    @iambox what if DatabaseHelper needed a FragmentActivity instead of an Activity? For example, for an Adapter...
  • personne3000
    personne3000 about 10 years
    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.
  • Fattie
    Fattie about 10 years
    that's the context of the container, I think ... not "this context".
  • vovahost
    vovahost over 9 years
    If you store a reference to your activity in onAttach(Activity activity) then you should release it in onDetach()
  • tyczj
    tyczj over 9 years
    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?
  • Sotti
    Sotti about 9 years
    @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?
  • personne3000
    personne3000 about 9 years
    @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#Lifecy‌​cle 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.
  • Machado
    Machado about 9 years
    @AG1 could you please explain why did it crashed your code? This is so far the best solution I've got
  • Lucas Teske
    Lucas Teske almost 9 years
    Actually on dialogFragments the container can be null. Be carefull!
  • Peter Mortensen
    Peter Mortensen over 8 years
    How is this different from Ankur Chaudhary's answer?
  • JHH
    JHH over 8 years
    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.
  • Muhammad Saqib
    Muhammad Saqib about 7 years
    The onAttach method has been deprecated, Overrides deprecated method in 'android.support.v4.app.Fragment'
  • Izkata
    Izkata almost 6 years
  • Ade
    Ade over 5 years
    Thanks for availing a Kotlin version, which works fine, however I am trying to get Context for Picasso.get(), with it and it never works, I have tried all i can from samples above as well to get context. At best I get this message -Too many arguments passed... Please help. val ctx = context ?: return Picasso.get(ctx) .load(selectedGallery.imageUrl) .placeholder(R.mipmap.ic_launcher) .into(galleryImage)
  • Kishan Solanki
    Kishan Solanki over 5 years
    @Ade In your fragment, try to use "activity!!" instead of "ctx" and let me know it helps or not
  • Ade
    Ade over 5 years
    @ KishanSolanki124. Thanks very much for the quick response. I tried your suggestion, with the same result - Not working still. The exact error prompt is - Too many arguments for public open fun get(): Picasso!. This message makes me think, maybe something else is the error?. Gladly though, found a way to move on with my work by using Picasso without getting context. Thanks again.
  • Geoff
    Geoff over 4 years
    This is now deprecated in androidx
  • help-info.de
    help-info.de over 4 years
    There are other answers that provide the OP's question, and they were posted some time ago. When posting an answer see: How do I write a good answer?, please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions.
  • fisio
    fisio about 4 years
    This solution should be used in onViewCreated, not onCreateView.
  • Gabriele Mariotti
    Gabriele Mariotti about 4 years
    Context != ApplicationContext
  • Daxesh Vekariya
    Daxesh Vekariya almost 4 years
    Yes, Its good solution but need to be test various cases.
  • YaMiN
    YaMiN about 2 years
    How requireContext() is considered correct when it may throw an exception? I believe it's a harmful way to use.