Fragments do not have their own Context; they use parent activity.
- To get the parent activity context, use
getActivity() - To use the application context, use
getActivity().getApplicationContext()
Prefer application context where possible.
UPDATE:
getActivity() fragment returns an instance of an Activity if and only if the specified fragment is currently bound to an Activity.
So,
Fragment f = new MyFragment();
creates a fragment, but it is not yet tied to activity. Therefore, f.getActivity() returns null .
After adding it to the action:
getFragmentManager().beginTransaction().add(f,"fragment").commit();
Now getActivity() will return an instance of Activity.
Again, if we separate the fragment from the Activity:
getFragmentManager().beginTransaction().detach(f).commit()
getActivity() will return null again.
Therefore, we should not use getActivity() outside the Fragment class, because we cannot be sure of the attached state. Thus, I advise you to use getActivity() inside your own fragment class in your methods: onAttach() , onCreate() or onActivityCreated() .
source share