How can I get the context in a fragment?
I need to use my database whose constructor takes in the context, but getApplicationContext()
and Fragmen
You have different options:
getActivity()
, since this is a Context
.getContext()
.If you don't need to support old versions then go with getContext()
.
On you fragment
((Name_of_your_Activity) getActivity()).helper
On Activity
DbHelper helper = new DbHelper(this);
You can use getActivity(), which returns the activity associated with a fragment
.
The activity is a context
(since Activity
extends Context
).
With API 29+ on Kotlin, I had to do
activity?.applicationContext!!
An example would be
ContextCompat.getColor(activity?.applicationContext!!, R.color.colorAccent),
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)
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;
}
}
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
,
requireContext() method is the simplest option
requireContext()
Example
MyDatabase(requireContext())