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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With