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
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
context=activity;
}
Also you can use:
inflater.getContext();
but I would prefer to use
getActivity()
or
getContext
You could also get the context from the inflater
parameter, when overriding onCreateView
.
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* ... */
Context context = inflater.getContext();
/* ... */
}
}
to get the context inside the Fragment will be possible using getActivity() :
public Database()
{
this.context = getActivity();
DBHelper = new DatabaseHelper(this.context);
}
Activity
associated with the fragment using getActivity()
, you can use it but is not recommended it will cause memory leaks.I think a better aproach must be getting the Activity
from the onAttach()
method:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
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 activity
this.getContext()
will give you a handle to the context
this.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.
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();