0

I am using asynctask in one of my fragment. but when press back before completion of asynctask the app crashes. I am calling asynctask in onstart method of fragment.

this is my onStart method of fragment where I am executing the asynctask.

public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    new FetchTableTask().execute();

}

what should I add in the code so that even when the asynctask is incomplete the app would not crash.

Ankita Deshmukh
  • 227
  • 3
  • 12

1 Answers1

0

Maybe call cancel on the async task when back is pressed and then add conditions in your code to check if it has been cancelled, so it doesn't do whatever is causing your crash.

Here is the example from the documentation, notice the isCancelled() call.

 protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
bracken
  • 374
  • 2
  • 3