0

I have an AsyncTask executing multiple AsyncTasks (calling a web service).

I'm looking for a way to make my AsyncTask waiting for others AsyncTask responses

to be able to give "main" AsyncTask response

public class MainTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {
          for (int i=0 ; i<myObjects.size();i++) {
                MyObject m=myObjects.get(i);
                creationTask=new CreationTask();
                //init creationTask
                creationTask.execute(new String[] { URL });
          }
            //wait for creationTasks responses
            //return "success" if all succeeded
     }
}

Task launched by MainTask

   public class CreationTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
               //Creation request to web Service
              return result;
        }
        @Override
        protected void onPostExecute(String result) {
            if ("success".equals(result)) {
                //notify MainTask
            }
        }
     }

Thanks in advance

Matt Taylor
  • 3,360
  • 1
  • 20
  • 34
Simo
  • 1,200
  • 1
  • 16
  • 26
  • Don't use asynctasks inside a asynctask, convert your nested asynctask to a method en then run that, that way it will run synchronous inside your thread. – ePeace Apr 24 '13 at 10:06

3 Answers3

1

You can call the doInBackground method of other AsyncTasks from the doInBackground of your main one.

public class MainAsyncTask<?, ?, ?>{
    doInBackground(){
        new OtherAsyncTask().doInBackground();
        new AnotherAsyncTask().doInBackground();
    }
}

Or, better yet, split your code up a bit so the AsyncTasks aren't in charge.

alex
  • 6,359
  • 1
  • 23
  • 21
0

You should run your tasks implementing an interface (observer design pattern) with a callback, and after every one of them has been completed, you'll be able to do whatever you want in the calling thread. But I wouldn't start asyncTasks from inside a doInBackground(), you should do that from the main (UI) thread.

Analizer
  • 1,594
  • 16
  • 30
0

You can exceute your AsynTask2 or AsyncTask3 in the OnPostExecute() of AsyncTask1 . But Observer design pattern is good approach for doing this.