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
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 ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
Inside fragment for kotlin sample would help someone
textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
if you use databinding;
bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
Where bindingView is initialized in onCreateView like this
private lateinit var bindingView: FragmentBookingHistoryDetailBinding
bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)
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()
*/
@Nullable
final public FragmentActivity getActivity() {
return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}
and
/**
* Return the {@link Context} this fragment is currently associated with.
*
* @see #requireContext()
*/
@Nullable
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}
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.
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.
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.
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.