Using context in a fragment
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),
tyczj
Updated on July 21, 2022Comments
-
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()
andFragmentClass.this
don't work so what can I do?Database constructor
public Database(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); }
-
arne.jans about 11 yearsI would recommend this, as getActivity() returns null if onAttach isn't called yet.
-
Zordid about 11 yearsBut, keep in mind, when onAttach() is called, there are no views. So you cannot do anything with views yet!
-
Jago about 11 years@iambox what if
DatabaseHelper
needed aFragmentActivity
instead of anActivity
? For example, for anAdapter
... -
personne3000 about 10 yearsI 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 about 10 yearsthat's the context of the container, I think ... not "this context".
-
vovahost over 9 yearsIf you store a reference to your activity in
onAttach(Activity activity)
then you should release it inonDetach()
-
tyczj over 9 yearsYou 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 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 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#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.
-
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 almost 9 yearsActually on dialogFragments the container can be null. Be carefull!
-
Peter Mortensen over 8 yearsHow is this different from Ankur Chaudhary's answer?
-
JHH over 8 yearsThis 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 throughsetContentView
). In your correct example you are callingView.findViewById
, notActivity.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 about 7 yearsThe
onAttach
method has been deprecated,Overrides deprecated method in 'android.support.v4.app.Fragment'
-
Izkata almost 6 years@MuhammadSaqib Official docs give no indication it was deprecated
-
Ade over 5 yearsThanks 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 over 5 years@Ade In your fragment, try to use "activity!!" instead of "ctx" and let me know it helps or not
-
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 over 4 yearsThis is now deprecated in androidx
-
help-info.de over 4 yearsThere 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 about 4 yearsThis solution should be used in onViewCreated, not onCreateView.
-
Gabriele Mariotti about 4 yearsContext != ApplicationContext
-
Daxesh Vekariya almost 4 yearsYes, Its good solution but need to be test various cases.
-
YaMiN about 2 yearsHow
requireContext()
is considered correct when it may throw an exception? I believe it's a harmful way to use.