1

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()?

Ben Neill
  • 2,811
  • 2
  • 22
  • 20
  • On the surface, can't fault your code at all. You are firing a new instance so you really shouldn't be getting that exception. Are you by any chance resuming the app in between (from background) or something to that effect? – dineth Sep 11 '12 at 23:34
  • Also which version of Android is this running on? – dineth Sep 11 '12 at 23:39
  • This is coming from debug info from test users, I specifically found the 'second execution' issue and replaced with this, so I am quite surprised to see it. It is running on 4.0.3 – Ben Neill Sep 11 '12 at 23:43
  • Not quite sure how they triggered this so might try causing resume. – Ben Neill Sep 11 '12 at 23:44
  • Let me post in the answer section as what I want to say will not fit here. I was reluctant to post as answer due to the fact that I don't know the actual problem... :p – dineth Sep 11 '12 at 23:49
  • http://stackoverflow.com/a/6879609/2624806 might help here :) – CoDe Mar 01 '14 at 18:43

1 Answers1

2

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

dineth
  • 9,822
  • 6
  • 32
  • 39
  • I've still not been able to recreate this issue so I am going to chalk it up to an issue with the bug reporting, or a glitchy build. Voting to delete. Thanks for the time @dineth – Ben Neill Sep 26 '12 at 07:18