0

my data is load from the internet, so I use the AsynTask(). execute() method to open a progressDialog first, then load the data in the background. it works, however, sometimes it takes too long to load the data so I want to cancel loading, and here is the problem: when I click back button the dialog dismiss but after it finish loading at the background, it start to do whatever it supposed to do after loading, e.g. start a new intent. is there any way I can cancel the loading properly???

new GridViewAsyncTask().execute();
public class GridViewAsyncTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog myDialog;

    @Override
    protected void onPreExecute() {
        // show your dialog here
        myDialog = ProgressDialog.show(ScrollingTab.this, "Checking data",
                "Please wait...", true, true);

    }

    @Override
    protected Void doInBackground(Void... params) {
        // update your DB - it will run in a different thread
        loadingData();

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // hide your dialog here
        myDialog.dismiss();
}
Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
Ricky Zheng
  • 1,279
  • 3
  • 16
  • 27
  • http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask this link is much better! – Ricky Zheng Jul 22 '12 at 13:50

2 Answers2

2

Call mAsycntask.cancel(); when you want to stop the task.

Then

@Override
protected Void doInBackground(Void... params) {
    // update your DB - it will run in a different thread

    /* load data  */
    ....
    if (isCancelled()) 
       return;
    /* continue loading data. */

    return null;
}

Documentation: http://developer.android.com/reference/android/os/AsyncTask.html#isCancelled()

Ron
  • 24,175
  • 8
  • 56
  • 97
1

Declare your AsyncTask like asyncTask = new GridViewAsyncTask();

Then execute it as you did it before (asyncTask.execute();) and to cancel it:

asyncTask.cancel();

Add the onCanceled method to your AsyncTask class and override it. Perhaps to show a Log or something else!

@Override
protected Void onCancelled () {
    // Your Log here. Will be triggered when you hit cancell.
}
yugidroid
  • 6,640
  • 2
  • 30
  • 45