Ben Neill
Ben Neill

Reputation: 3009

Calling a re-instantiated async task failing with 'task has already been executed'

I have a search task which when the button is clicked a second time, it cancels the currently running task and recreates it.

if (_searchAsyncTask != null) {
    // cancel if already running
    _searchAsyncTask.cancel(true);
}
_searchAsyncTask = new SearchAsyncTask(this);
_searchAsyncTask.execute(data);

This is failing on the last line in the above code as if I had called the original async task again.

java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)

Am I missing something? Do I need to wait until the original instance isCancelled()?

Upvotes: 1

Views: 3382

Answers (1)

dineth
dineth

Reputation: 9942

Recently I had this odd problem where it was bombing out with a similar exception when resuming from background and the task had been running halfway through when it went to the background. I switched to using AsyncTask.executeOnExecutor to fix this (some code may be redundant):

if (_searchAsyncTask == null) {
    _searchAsyncTask = new SearchAsyncTask();
}

if (mThreadExecutor != null && !mThreadExecutor.isShutdown()) {
    mThreadExecutor.shutdownNow();
}

if (mThreadExecutor == null || mThreadExecutor.isShutdown()) {
    mThreadExecutor = Executors.newSingleThreadExecutor();
}

if (_searchAsyncTask.getStatus() != Status.RUNNING) {
    _searchAsyncTask.executeOnExecutor(mThreadExecutor);
}

This solved my problems. You might want to give it a shot...?

Upvotes: 2

Related Questions