0

I have an asynctasks. In oncreate view of a dialog fragment i am creating the object of my asynctask Like below (Sample code)

      @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

  cashInValidatorListner = new CashInValidatorListner(mSessionManager.getCustomerId(),mSessionManager.getPosId(), this);
        }

Now in onclick i am executing the async taks

  @Override
public void onClick(View v) {
    if(v==ok)
     {
         if(mHomeActivity.mProgressDialog!=null && !mHomeActivity.mProgressDialog.isShowing()){
            mHomeActivity.mProgressDialog.show();
        }
         cashInValidatorListner.execute();
    }
    }

I have added oncancellistner for this progressbar

       @Override
public void onCancel(DialogInterface dialog) {

    if(dialog==mProgressDialog)
    { 
        mDialogExtraOptions.cashInValidatorListner.cancel(true);
        Toast.makeText(getBaseContext(), "Task Cancled", Toast.LENGTH_SHORT).show();
    }
}

The first time i cancel the async task it get cancelled howerver on executing it again it gives error saying can not execute task already executed .

When i tried creating the object at onclick each time user click ok button the problem is solved Like this

        @Override
public void onClick(View v) {
    if(v==ok)
     {
         if(mHomeActivity.mProgressDialog!=null && !mHomeActivity.mProgressDialog.isShowing()){
            mHomeActivity.mProgressDialog.show();
        }
           cashInValidatorListner = new CashInValidatorListner(mSessionManager.getCustomerId(),mSessionManager.getPosId(), this);
         cashInValidatorListner.execute();
    }
    }

Here it works fine ,My question why the async task was not executing when i was running it second time in first case ?

Bora
  • 1,933
  • 3
  • 28
  • 54

2 Answers2

2

You may only execute an Asynctask once in an instance's lifetime. This is solved by simply creating a new instance of the Asynctask object and executing the newly created object, like you have done.

 (new CashInValidatorListner(mSessionManager.getCustomerId(),mSessionManager.getPosId(), this)).execute();
frogmanx
  • 2,620
  • 1
  • 18
  • 20
  • Is creating new instance is a bad idea here ?and i should try to create only one object and try to cancel that once ? – Bora Jul 01 '13 at 11:25
  • you can just execute on the same line instead of assigning it to a variable everytime – frogmanx Jul 01 '13 at 11:30
0

Quote form the docs.

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

You will get IllegalStateException Cannot execute task: the task is already running.

AsyncTask instances can only be used one time.

Check the topic under Threading rules.

http://developer.android.com/reference/android/os/AsyncTask.html

To cancel the asynctask call cashInValidatorListner,cancel(true).

If you call cancel(true), an interrupt will be sent to the background thread, which may help interruptible tasks. Otherwise, you should simply make sure to check isCancelled() regularly in your doInBackground() method.

protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }

Source : Android - Cancel AsyncTask Forcefully

public final boolean cancel (boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

Use isCancelled()

public final boolean isCancelled ()

Returns true if this task was cancelled before it completed normally. If you are calling cancel(boolean) on the task, the value returned by this method should be checked periodically from doInBackground(Object[]) to end the task as soon as possible.

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256