0

I have created an Android Application, in that I want to cancel AsyncTask onPause state of Fragment.

I tried using AsyncTask.cancel(true); but it gives null pointer exception.

@Override
public void onPause()
{
    super.onPause();
    AsyncTask.cancel(true);
}

Thanks.

Sagar Zala
  • 4,854
  • 9
  • 34
  • 62

2 Answers2

0

task.cancel() will do it. Be sure to include frequent checks to isCancelled() in your onBackground() as well as in onPostExecute() to avoid accessing/updating UI which is no longer there.

public void onActivityPause() {
    task.cancel();
}
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
0

asyncTask.cancel(true); will change a boolean value only and don't stop your thread. so you need to "ask" if the async task not cancelled.

example:

@Override
protected Void doInBackground(Void... params) {
    while(!isCancelled()){
        // do something
    }
    return null;
}
Liran Peretz
  • 580
  • 8
  • 11