0

In one activity if i want to make 2-3 REST API calls one after the other as per below example.

task1.execute(); /*calls API1*/
while(task1.getStatus().equals(AsyncTask.Status.FINISHED)){
    task2.execute(); /*calls API2*/
    };

    while(task.getStatus().equals(AsyncTask.Status.FINISHED && task1.getStatus().equals(AsyncTask.Status.FINISHED)){
    task3.execute(); /*calls API3*/
        };

AsyncTask.Status is always showing running even after getting the response. Can you please help me on this.

http://stackoverflow.com/questions/12776293/how-to-get-asynctask-completed-status-from-non-activity-class/27666709#27666709
bpetlur
  • 333
  • 5
  • 16

2 Answers2

1

In the onPostExecute callback for the initial task, call execute on the next task. This will chain them together without needing to monitor status explicitly.

stkent
  • 19,772
  • 14
  • 85
  • 111
0

AsyncTasks are run by default on the serial executor. That means the calls DO happen one at a time (by default).

By the way, your while loop is not correct - it will never even enter the loop since the task is not finished immediately after you start it.

Greg Ennis
  • 14,917
  • 2
  • 69
  • 74
  • Ah, interesting (about the single-thread execution). Even more reason to adhere to the recommendation that AsyncTasks be used only for short (2-3 second) operations. – stkent Dec 28 '14 at 04:22
  • 1
    Yeah, it also depends on if he is targeting an old SDK version, in that case the thread pool executor is the default and he should use your answer. Or if he wants to cleanly pass data from one to the next he should probably use your answer. But really you wonder why he is trying to do this. – Greg Ennis Dec 28 '14 at 04:26
  • I tried some thing like below myAsyn asyn = new myAsyn(); asyn.execute(); while(asyn.getStatus()!=Aynctask.Status.Finished) { Thread.sleep(100); } But still the status is in RUNNING state. Is there any way can i get the status FINISHED, so that i can execute next API call. – bpetlur Dec 29 '14 at 12:25
  • You must not call Thread. Sleep on the UI thread for the same reason you could not make the network calls! Is there a reason either one of the two answers posted here works for you? – Greg Ennis Dec 29 '14 at 12:37