AsyncTask onPostExecute never gets called
Note that if you cancel the task via cancel()
, onPostExecute()
won't be called. Pretty logical, but simply overlooking a call to that method had me stumped.
I had a similiar problem just now. I was extending AsyncTask<Integer,Integer,Integer>
and my onPostExecute method looked like:
protected void onPostExecute(int result)
This seemed OK to me, but then again I'm more of a .NET guy than a Java guy. I changed it to:
protected void onPostExecute(Integer result)
because for some reason Java thinks there is a difference between int
and Integer
?
I think that your problem is that you're declaring the return type as void
in your:
extends<Void,Void,Void>
That means no params, no progress and no result. If you want to execute something when it's done, I think you need to give it some kind of value like and integer or a boolean.
If you change your extends to:
<Void,Void,Integer>
Now your passing no params, not publishing any progress, but are returning a value. Change your onPostExecute
method to accept an Integer
:
protected void onPostExecute(Integer result)
Then change the return in your doInBackground
method to something like:
return 1;
Then it should execute for you.
There's one more gotcha about AsyncTasks that I just spent half the day on:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
Says the documentation. On Gingerbread (and probably before), given the right circumstances, this leads to onPostExecute
not being run. The solution, however, is easy, just a
new MyAsyncTask();
early in the UI thread so the class gets loaded before anything in the background can inadvertently load it.
I had used a static function in my AsyncTask subclass from a background thread that, depending on timing, got called before anything on the UI thread used that AsyncTask subclass, and bingo, a nice Heisenbug.
(Bear with me for answering this old, already answered question, but I didn't find that tidbit of info anywhere, and this is my first post)
My problem was that somehow I didn't @Override the onPostExecute method correctly. I fixed that by clicking right mouse button->source-> Override\Implement method.
Hopes it helps someone