user7908423
user7908423

Reputation:

Execute Async Tasks one after another

I know that there are already some discussions and I searched on the internet a lot for a solution, I have 3 get calls (volley) I want to execute one after another because the next get does need variables which were set on the get before this but it doesn't seem to work here. When I debug the whole process it worked fine of course but when running the app normally it doesn't get any data which I would have gotten when debugging it.

Now I tried to set static boolean variables to make this whole thing work but theres so far no success..

public class AsyncToken extends AsyncTask<String , Void, Void> {

private PacketBuilder pb = new PacketBuilder();
private Context context;
AsyncUser u = new AsyncUser(context);

@Override
protected Void doInBackground(String... params) {

    while( task1finished == false )
    {
        try
        {
            Log.d("App", "Waiting for GetTask");
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    Log.d("App", "GetTask finished");
    // Do what ever you like
    // ...
    pb.Get("token", "", params[0], context);

    return null;
}

protected void onPostExecute(String ... params)
{
    task2finished = true;

}

public AsyncToken(Context context)
{
    this.context = context;
}

}

EDIT, the code: Code where i start the first asynctask, in the end i check if the object i should have gotten with get is there, if yes, i start another activity

first asynctask

last asynchtask

Upvotes: 0

Views: 812

Answers (1)

When async task is completed onPostExecute() is called, so start another async task with computed values there. You can have global variables what should be computed or you can pass them through parameters.

//start first async task
new TaskOne().execute();


class TaskOne extends AsyncTask<Void,Void,String>{
    String tmp;


    @Override
    protected String doInBackground(Void... records) {
        tmp = computeNeededValue();

        return tmp;
    }

     @Override
    protected void onPostExecute(String result) {
        new TaskTwo().execute(tmp);
    }
)

class TaskTwo extends AsyncTask<String,Void,Void>{

    @Override
    protected Void doInBackground(String... records) {
        //use computed value from first task here 
    }

     @Override
    protected void onPostExecute(Void result) {
        //start another async task
    }
)

Upvotes: 2

Related Questions