Search code examples
androidandroid-asynctaskbackground-task

Wait for AsyncTask to finish before looping array


I have a loop which assigns a candidate ID to a variable, which is used in my background task to retrieve data from the db. But as it is a background task, by the time the task is getting to run, it is only using the last ID:

for (int i=0; i < id_array.length; i++) {
    System.out.println("array");
    System.out.println(id_array[i]);
    candidate_id = id_array[i];
    new BackgroundTask().execute();
}

It is looping correctly (can see from my outputs) but it is the same ID each time when I call candidate_id in the background task. I am using it as part of a URL JSON request:

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

    String json="http://[myip]/dan/db/getcandidatedetails.php?candidate_id=";

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

        System.out.println("Candidate ID******" + candidate_id);

        String json_url= json + candidate_id;

        System.out.println("url" + json_url);

...

The candidate ID that it returns is always the last one in the loop.

Any suggestions of how to solve this/a more efficient way of doing this?


Solution

  • You should pass that value as a parameter to your AsyncTask:

    public static class MyAsyncTask extends AsyncTask<Integer, Void, String> {
    
        @Override
        protected String doInBackground(final Integer... integers) {
            final int candidateId = integers[0];
            // do some work here with `candidateId`
            return "some_string";
        }
    }
    

    Then when executing AsyncTask:

    new MyAsyncTask().execute(candidateId);