Android AsyncTasks ,One after the other

While doing development in Android, Its  always recommended that we must perform the long running task like calling some kind of URL and receiving response from it on some back ground thread rather than on the UI thread.

The good thing about the  AsyncTask’s  is that they provide you with the methods likeonPreExecute() and onPosteExecute() which can be used(if you want to) interact with the UI, andplace your long running process in the doInBackground() of the AsyncTask.There is another method called onProgreessUpdate() which you can utilize too.

image

If you are already aware of the above things than you will be knowing that how to start an AsyncTask.

Just make an object of the class extending the AsyncTask class and call .execute on it. like

MyAsycTask.execute();

Now this was all a happy going,but lets just consider a tedious situation where you want to call up a URL,get the response and according to the received response you want to call another URL.That is we are looking to make two httpPosts requests,but to make it more modular and save ourselves from tedious Exception Handling,we can perform these tasks in two different AsyncTasks.

Let the first AsyncTask is MyAsyncTask1 and the second one is MyAsyncTask2. Now what we want is.

  1. Execute the MyAsyncTask1 from with in the activity
  2. Take the response received
  3. Now on successfull response,execute the MyAsyncTask2

what about calling them in sequence like:

MyAsyncTask1.execute();

MyAsyncTask2.execute();

The problem with the above code can be understood by the fact that calling execute on the AsyncTask object will create a  new thread to run in different memory space,and immediately the next AyncTask will be started with in its own memory space.But that was not what we want.We want that the first thread must finish its working and only then the second one will start to work.How this can be achieved?

The answer lies in the onPostExecute().This is the method which will help you to get rid of this situation.While you call execute on MyAsyncTask1 then after doInBackground() of the first AsyncTask its,onPostExecute() will be called .Place a check in that onPostExecute() that if response is null, if received response is not equal to null,and is a valid response then call execute on the MyAsyncTask2(with respective parameters if specified).

image

This way you can have the track of the background processes and let the second one start after the first have finished its work.