質問

I'm facing a little issue with my AsyncTask. I run the asynctask in this way:

myTask = new myTask();

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String s) {
                    // same as onquerychange
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String s) {
                    if (!s.isEmpty()) {
                        if (myTask.getStatus() == AsyncTask.Status.RUNNING ||
                                myTask.getStatus() == AsyncTask.Status.PENDING) {
                            myTask.cancel(true);
                        }
                        myTask.execute(context, s);
                    } else {
                        myTask.execute(context, "emptyquery");
                    }
                    return true;
                }
            });

Once i type the second letter i keep getting: java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)

So i assume it doesn't get cancelled. Any suggestions? Thanks

役に立ちましたか?

解決

You cannot execute the same AsyncTask more than once. You'll have to instantiate it before executing it each time, e.g.:

myTask = new myTask();
myTask.execute(context, s);

Of course you can then remove the initialization at the beginning.

For stopping and restarting, use:

myTaks.cancel(true);
myTask = new myTask();
myTask.execute(context, s);

Even though you cancel the AsyncTask, you cannot use it again.

他のヒント

When you call myTask.cancel(); the AsyncTask try to stop the thread. to force that, you can check if the task has been cancelled with:

if(isCancelled()){
   return null;
}

inside the doInBackground and block it by yourself. Otherwise the status of the AsyncTask has been checked before to call the onPostExecute. in this way if you call the cancel() you are sure that no value is returned. check the doc here: AsyncTask

and anyway: an AsyncTask can be executed only once. you have to instantiate another AsyncTask if you have to run it again.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top