i am importing contacts in to a file using asynchronous task it is going well but after starting asynchronous task if i want to cancel it on middle then how to stop it means which have been done before stooping async task should be null and stop the asynch task..my code is below pls help me..
-
1try this `new asynctask().cancel(mayInterruptIfRunning);` – Nikunj Patel Dec 07 '11 at 09:11
-
see this http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask and also this http://stackoverflow.com/questions/6039158/android-cancel-async-task – MKJParekh Dec 07 '11 at 09:16
-
and in above they have used while condition for continuously fetching data one bye one..so when the boolen var is true they stops the loop and comes out of the doInBackground. – MKJParekh Dec 07 '11 at 09:19
3 Answers
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true
. After invoking this method, onCancelled(Object)
, instead of onPostExecute(Object)
will be invoked after doInBackground(Object[])
returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled()
periodically from doInBackground(Object[])
, if possible (inside a loop for instance.)

- 108,599
- 23
- 164
- 151
-
hi..i am using. cancel.setOnClickListener(new OnClickListener(){ public void onClick(View v) { boolean mayInterruptIfRunning = true; new createCSV().cancel(mayInterruptIfRunning); } }); and in do in back ground i use while (isCancelled()) { if (isCancelled()) { Log.i("#################","true value"); break; } } return null; } but not working..:( – shyam Dec 07 '11 at 11:04
-
cancel is the object of button ,on click cancel button i want to stop async task and why the problem is on new createCSV().cancel(mayInterruptIfRunning); i m not getting.. – shyam Dec 07 '11 at 11:11
-
In your activity's onCreate() initialize AsyncTask class's object and use the same object for execute and for cancel() have you got it..? – user370305 Dec 07 '11 at 11:35
-
AsyncTask
createCSV = new AsyncTask – user370305 Dec 07 '11 at 11:38() { } like this, and in your activity use createCSV.execute() and on cancelButton just createCSV.cancel(mayInterruptIfRunning);
Override the method onCancelled()
and in that set flag canceled = true;
and pass this canceled variable to condition in doInBackground
.

- 232,980
- 40
- 330
- 338

- 4,324
- 4
- 28
- 54
I would have while(!iscancelled()) as the while condition. So when your cancel button is pressed, call cancel(true) on your AsyncTask. This will cause the while condition to be false. doInBackground will then exit.
If you implementation onCancel this will be called after doInBackground and you can set the contacts to null.
Hope that helps.

- 4,037
- 6
- 41
- 68