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
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()
.
Since API level 23 there is getContext()
but if you want to support older versions you can use getActivity().getApplicationContext()
while I still recommend using the support version of Fragment
which is android.support.v4.app.Fragment
.
I think you can use
public static class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getActivity.getContext();
}
}
You can use getActivity() method to get context or You can use getContext() method .
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
Context c = root.getContext();
I hope it helps!
Another alternative approach is:
You can get the context using:
getActivity().getApplicationContext();
getActivity()
is a child of Context so that should work for you