Alper Özdemir Alper Özdemir - 2 months ago 11
Android Question

Waiting for other AsyncTasks' finish in AsyncTask before processing onPostExecute

I'm getting info from an URL and sending that info to multiple URLs. I'm running it on a "for" in

AsyncTask
, and at onPostExecute of first
AsyncTask
, I change a
TextView
and telling that "All is done" to user.

But the thing is even the children of
AsyncTask
is continuing to being executed, parent
AsyncTask
executes its
onPostExecute
. So I need to wait for them and I'm stuck about it.

So, I have two AsyncTask classes. That's the class I send to websites:

class SendTo extends AsyncTask <Object,Object,String>{

@Override
protected String doInBackground(Object... strings) {
....
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
//update ui for gathered information
}

}


That's the task which I get from websites:

class GetFrom extends AsyncTask <Object,Object,String>{

@Override
protected String doInBackground(Object... strings) {
....
String param = anotherMagicalFunctionThatGivesParamToSend(strings[1]);
for(i = 1; i < websites.length; i++){
publishProgress(websites[i],param);
}
return "";
}
protected void onProgressUpdate(final Object... values) {
super.onProgressUpdate(values);
new SendTo().executeOnExecutor(THREAD_POOL_EXECUTOR, values[1], values[0]);
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
//finish things
}
}

Answer
  1. Run following for loop inside postExecute() of asyncTask as it's anyway not useful running thread inside the thread.

  2. Maintain one global variable which will have count of completed asyncTasks and will be incremented by 1 when each asyncTask will completes it's execution. i.e it will come into postExecute.

  3. In Every postExecute check if that count is equal to number of websites. If that number will be equal to number of websites that basically means all of your data is successfully synced else it's still in process.

Comments