5

There is a similar question where most answers advice to use getActivity() in order to obtain the context of a fragment, but how to get a reference to the activity/context if the fragment is detached (in which case, getActivity() returns null)?

My situation is that my fragment starts an AsyncTask which, on completion, calls the onSuccess() method of my fragment. But my fragment's onSuccess() method requires a context in order to show a Toast message or to access the shared preferences. So is there a reliable way of obtaining the context?

One way I'm considering is to pass a context object into my AsyncTask constructor, and pass it back out to my aforementioned onSuccess() callback method - but could this result in a memory leak?

(NB - There's an answer here that shows how to retrieve the current activity but, again, it requires a valid context.)

Community
  • 1
  • 1
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253

2 Answers2

3

Use this in your fragment:

private Context context;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}

then use context where you want.

frogatto
  • 28,539
  • 11
  • 83
  • 129
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78
0

You should store the context after creating view, when you enter in fragment.

    Context context;

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
        MainView = rootView;
        context = getActivity().getApplicationContext();
        return rootView;
    }

use that context in your fragment, where ever you want.

Anuj Sharma
  • 4,294
  • 2
  • 37
  • 53