0

I need to cancel my AsyncTask with a button in the progress dialog.

I've created the Progress dialog with the button. Here it is:

@Override
protected void onPreExecute() {
    pDialog = new ProgressDialog(DSDactivity.this);
    pDialog.setMessage(getResources().getString(R.string.pDialog));
    pDialog.setCancelable(false);
    pDialog.setButton("Cancel", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            pDialog.dismiss();
            asyncCodelist.cancel(true);

        }
    });
    pDialog.show();
}

I have two problems:

  1. When I click "cancel" on the progress dialog is removed but the async task continues to do what he was doing

  2. Eclipse gives me this waning:

The method setButton(CharSequence, DialogInterface.OnClickListener) from the type AlertDialog is deprecated

uynva
  • 97
  • 1
  • 16
  • already you are making pDialog.setCancelable(false); so how u can dismiss that? – Shadow Nov 10 '14 at 14:49
  • Here is what you're looking for : http://stackoverflow.com/a/7734109/4232337 – NSimon Nov 10 '14 at 14:49
  • @Shadow the process dialog working properly, the problem is another. – uynva Nov 10 '14 at 14:52
  • @NSimon I had already seen this. But do not think I can help, please create a button on the progress dialog. – uynva Nov 10 '14 at 14:53
  • http://stackoverflow.com/a/12115431/609782 and you can set a button , where in `onClickListener()` you can cancel your task by `myTask.cancel();` – Darpan Nov 10 '14 at 15:14

2 Answers2

0
@Override
protected void onPreExecute() {
  pDialog = new ProgressDialog(DSDactivity.this);
  pDialog.setMessage(getResources().getString(R.string.pDialog));
  pDialog.setCancelable(true);
  pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      myTask.cancel(true);
      dialog.dismiss();
    }
  }
}

And then, as my link said, create your AsyncTask and store it :

MyAsyncTask myTask=null;

and execute it like this :

myTask = new MyAsyncTask();
myTask.execute();
NSimon
  • 5,212
  • 2
  • 22
  • 36
0
  1. Asynctask won't stop completely only by myTask.cancel(true);

As the document states:

 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.)

More Here

  1. setButton() method is deprecated now for ProgressDialog, hence the warning. It will definitely work though.
Atul O Holic
  • 6,692
  • 4
  • 39
  • 74