I was constantly upset about this, and I can’t find a good answer, so I hope that someone here can offer guidance.
I have a snippet that uses quite widely AsyncTask. I am constantly suffering from errors when a fragment calls getActivity(), which returns null. I assume that this is due to the fact that some method in the fragment is called before the action is connected or after it is disconnected.
What is the correct way to handle this in my code? I don’t want this idiom to be littered everywhere
Activity activity = getActivity();
if (activity != null) { // do something }
looking at documents Fragment, I can find a variety of possible interceptors to solve this problem: isDetached(), onActivityCreated(), onAttach(), isResumed(), etc. What is the right combination?
EDIT:
Several people suggested canceling tasks when paused, but that means the standard idiom,
new AsyncTask<...>.execute();
cannot be used. This means that every exec'd AsyncTaskmust be tracked to completion or canceled. I just never saw this in a sample code from Google or elsewhere. Sort of,
private final Set<AsyncTask<?>> tasks = new HashSet<>;
...
AsyncTask<?> t = new AsyncTask<...>() {
...
public void onPostExecute(...) {
tasks.remove(this);
...
}
}
tasks.add(t);
t.execute();
...
@Override
public void onPause() {
for (AsyncTask<?> t: tasks) {
t.cancel();
}
tasks.clear();
}
source
share