Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get context/activity in detached fragment?

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.)

like image 833
ban-geoengineering Avatar asked Oct 19 '22 16:10

ban-geoengineering


1 Answers

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.

like image 195
Milad Faridnia Avatar answered Oct 22 '22 09:10

Milad Faridnia