【问题标题】:Wait for AsyncTask to finish before looping array在循环数组之前等待 AsyncTask 完成
【发布时间】:2017-04-26 15:36:03
【问题描述】:

我有一个循环,它将候选 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);

...

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

关于如何解决这个问题/更有效的方法的任何建议?

【问题讨论】:

标签: android android-asynctask background-task


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2021-12-26
    • 1970-01-01
    • 2020-01-04
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多