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);
}
The simple way is to use
getActivity()
. But I think the major confusion of using thegetActivity()
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 thegetActivity()
to get the context of Activity.getActivity()
is a child of Context so that should work for yougetContext() method helps to use the Context of the class in a fragment activity.
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 callonCreateView
method at least here you are sure not to get null forgetActivity()
: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.Another alternative approach is:
You can get the context using: