【问题标题】:How to print the results of two async tasks on same list?如何在同一个列表上打印两个异步任务的结果?
【发布时间】:2016-09-13 08:06:58
【问题描述】:

目前我正在开发一个列出您附近酒店的应用程序。我正在使用 google Places API 网络服务,它运行良好。但是我想打印从当前位置到每个地方的位置的距离和持续时间。

为了列出酒店,我使用了一个 asynctask,然后解析 JSON 并将结果打印为列表,就像 UDACITY 的阳光应用程序一样。

但我想在每家酒店旁边打印距离和持续时间。但是对于距离,必须使用另一个 api。你能帮我看看这怎么可能?

也就是说,我实际上需要一个函数来计算在为列表创建最终字符串时的距离和持续时间,以便它可以附加到每个酒店名称。

【问题讨论】:

  • 我认为当酒店列表进入异步的 onPost 方法时,然后从列表中获取酒店并计算距离并添加到适配器以进行显示
  • 您必须根据您的酒店的某些 id 或名称合并两个同步 api 的结果,并在合并后扩展您的适配器
  • 但是如何合并呢?请帮我一些代码。我不是专家

标签: android json google-maps android-asynctask


【解决方案1】:

在您的情况下,您必须调用 api 最多 n+1 次 所以在代码的 doInBackground 方法中处理数据 示例 -

private class PrepareDataAsyncTask extends AsyncTask<Void, Integer, Void> {

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

        try {
            // call api here and get response here
            response = apiresult();
            JSONArray jsonArray = new JSONArray(result);
            for(int i=0;i<jsonArray.length();i++){
                // Call api and add distance and append result here for listing
            }
        } catch (Exception exception) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        super.onPostExecute(result);
        // Set adapter here
    }

}

【讨论】:

  • 无论如何我会尽量通知你:D,谢谢你的想法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
相关资源
最近更新 更多