在循环数组之前等待 AsyncTask 完成

Wait for AsyncTask to finish before looping array

我有一个循环将候选 ID 分配给一个变量,该变量在我的后台任务中用于从数据库中检索数据。但由于它是后台任务,当任务到达 运行 时,它只使用最后一个 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();
}

它正在正确循环(可以从我的输出中看到)但是每次我在后台任务中调用 candidate_id 时它都是相同的 ID。我将其用作 URL JSON 请求的一部分:

    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);

...

它returns的候选ID总是循环中的最后一个。

关于如何解决this/a更有效的方法有什么建议吗?

您应该将该值作为参数传递给您的 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";
    }
}

然后在执行的时候AsyncTask:

new MyAsyncTask().execute(candidateId);