I have used AsyncTasks
with my application, in order to lazy download and update the UI.
For now my AsyncTasks
updates the UI real simply:
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.
Check whether activity is running or not
if (!isFinishing()) {
// Do whatever you want to do
}
I will insist that you that if you Activity is not running why don't you cancel the AsyncTask? That would be a better and feasible solution. If you Application is running say you move from one Activity to another then it won't give error AFAIK.
But, I would insist to cancel the AsyncTask then you'r Activity is not running, you can check AsyncTask is running or not,
if(task != null && task.equals(AsyncTask.Status.RUNNING))
task.cancel(true);
You can cancel your asynctask in the activity's onDestroy
@Override
protected void onDestroy() {
asynctask.cancel(true);
super.onDestroy();
}
and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if(!isCancelled()) {
gender.setText(values[0]);
}
}
As this part of one training on Android Developers suggests, keep a WeakReference
on the UI element that needs to be updated after task is done and check if the reference is null
before using it. This helps not only in checking if the UI is still around, but also does not prevent UI elements from being garbage collected.
Shouldn't
if (gender) {
gender.setText(values[0]);
}
be enough?