【问题标题】:Get Weather status of multiple locations inside for loop android获取for循环android内部多个位置的天气状态
【发布时间】:2019-07-03 23:07:27
【问题描述】:

我正在为此开发一个天气应用程序,我正在使用黑暗天空 API,我想知道我存储在 ArrayList<LatLng> 中的一堆位置的天气状态。

我正在使用OKHttp 解析来自 API 的 JSON 数据,因此我尝试在 for 循环中循环整个获取过程,但它没有提供所需的输出。

private void beginTask(ArrayList<LatLng> arrayLis) { 
    //arraylis contains list of locations(LatLng)
    m = 0;
    startTask = true;

    for (int i = 0;i<arrayLis.size();i++) {
        double latitude = ((LatLng)arrayLis.get(i)).latitude;
        double longitude = ((LatLng)arrayLis.get(i)).longitude;
        String url = "https://api.darksky.net/forecast/APIKEY/"
                +latitude+","+longitude+"?units=si";
        LatLng mylatlng = new LatLng(latitude,longitude);
        startProcess(url,mylatlng);

        Log.i("GGGTT",""+latitude+", "+longitude);
    }
}

private void startProcess(String myurl, final LatLng myLatlng){
    OkHttpClient httpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(myurl)
            .build();

    Call call  = httpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String data = response.body().string();
            Log.i("DATASS",data);
            if (response.isSuccessful()){
                try {
                    getCurrentDetails(data,myLatlng);
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }
        }
    });
}

private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException{
    JSONObject main = new JSONObject(data);
    double la = main.getDouble("latitude");
    double lon = main.getDouble("longitude");
    JSONObject currently = main.getJSONObject("currently");
    String summary = currently.getString("summary");
    double temperature = currently.getDouble("temperature");
    String icon = currently.getString("icon");

    LatLng latLngo = new LatLng(la,lon);
    ter.add(latLngo);
    weatherInfo.add(icon);

    // Output here is not in the same order that I have passed 

    Log.i("LETSCHECK",""+la+", "+lon +icon);
}

我将值传递为:

  1. 19.21111,73.07729
  2. 19.20238,73.06582
  3. 19.19383,73.05362
  4. 19.18848,73.04221

但是getCurrentDetails方法里面的输出顺序不一样

  1. 19.19383,73.05362
  2. 19.20238,73.06582
  3. 19.18848,73.04221
  4. 19.21111,73.07729

我认为该方法在前一个循环完成之前没有等待。

是否有任何解决方案可以在不更改其顺序的情况下获取存储在ArrayList 中的所有位置的天气状态?

编辑

嗨,我已经通过这种方法按顺序获取数据并且工作正常,谢谢,但还有一个问题是我希望显示数据 4 次,因为 ArrayList 中有四个 LatLng 并且工作正常,但是当我尝试读取存储在另一个数组中的获取数据,它只显示 2 个项目而不是 4 个。

private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException{

    JSONObject main = new JSONObject(data);
    double la = main.getDouble("latitude");
    double lon = main.getDouble("longitude");
    JSONObject currently = main.getJSONObject("currently");
    String summary = currently.getString("summary");
    double temperature = currently.getDouble("temperature");
    String icon = currently.getString("icon");

    //Log.i("LETSCHECK",""+la+", "+lon +icon+",k");

    loopi++;
    Log.i("LETSCHECK",""+loopi);
    if (loopi < arrayList.size()) {
        getItAgain();
    } else if (loopi == arrayList.size()){
        for (String l:weatherInfo){
            Log.i("LETSCHECK",l); 
            //expected 4 items to show but its showing only 2 items
        }
    }

    Log.i("LETSCHECK",""+la+", "+lon +icon);
    weatherInfo.add(icon); 
}

private void getItAgain() {
    double latitude = ((LatLng)arrayList.get(loopi)).latitude;
    double longitude = ((LatLng)arrayList.get(loopi)).longitude;
    String url = "https://api.darksky.net/forecast/74d8feeda5ecf5ee6667d034778b239d/"
            +latitude+","+longitude+"?units=si";
    LatLng mylatlng = new LatLng(latitude,longitude);
    startProcess(url,mylatlng);
}             

【问题讨论】:

  • 这是因为网络调用是异步的。你可以做的是不用在 for 循环中调用,你可以一个一个地进行网络调用。如果第一次网络调用完成,则从数组中删除元素并执行下一次网络调用。
  • @IshanFernando 您好,感谢您的建议。如果您不介意,请给我一个可以帮助我的示例代码。谢谢你

标签: java android location okhttp weather-api


【解决方案1】:

网络调用是异步的,这是您在此处遇到的预期行为。如果您想在传递它们时对它们进行排序,那么您可能需要一种机制来等待前一个的网络调用完成,然后再次调用下一个。但是,这可能会增加等待服务器响应的延迟,因为您不会同时从服务器获取多个响应。

如果您想等待响应以保持排序方式,您可能只需要执行以下操作。

// Declare a global variable of the list of your locations. 
ArrayList<LatLng> arrayLis; 
int i = 0; 

// Just start the first task without the loop. 
double latitude = ((LatLng)arrayLis.get(i)).latitude;
double longitude = ((LatLng)arrayLis.get(i)).longitude;
String url = "https://api.darksky.net/forecast/APIKEY/"
        +latitude+","+longitude+"?units=si";
LatLng mylatlng = new LatLng(latitude,longitude);
startProcess(url,mylatlng);

现在在getCurrentDetails 函数中,您可能只需要执行以下操作。

private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException{
    JSONObject main = new JSONObject(data);
    double la = main.getDouble("latitude");
    double lon = main.getDouble("longitude");
    JSONObject currently = main.getJSONObject("currently");
    String summary = currently.getString("summary");
    double temperature = currently.getDouble("temperature");
    String icon = currently.getString("icon");

    LatLng latLngo = new LatLng(la,lon);
    ter.add(latLngo);
    weatherInfo.add(icon);

    // Now initiate the next call
    i++;
    if(i < arrayLis.size()) getItAgain();

    Log.i("LETSCHECK",""+la+", "+lon +icon);
}

public void getItAgain() {
    // Just start the first task without the loop. 
    double latitude = ((LatLng)arrayLis.get(i)).latitude;
    double longitude = ((LatLng)arrayLis.get(i)).longitude;
    String url = "https://api.darksky.net/forecast/APIKEY/"
            +latitude+","+longitude+"?units=si";
    LatLng mylatlng = new LatLng(latitude,longitude);
    startProcess(url,mylatlng);
}

更新

我不明白为什么它显示 2 而不是 4 个结果。但是,我认为您需要按如下方式修改代码。

private void getCurrentDetails(String data,LatLng myLatlng) throws JSONException {

    JSONObject main = new JSONObject(data);
    double la = main.getDouble("latitude");
    double lon = main.getDouble("longitude");
    JSONObject currently = main.getJSONObject("currently");
    String summary = currently.getString("summary");
    double temperature = currently.getDouble("temperature");
    String icon = currently.getString("icon");

    // Move this upto here
    weatherInfo.add(icon);

    loopi++;
    Log.i("LETSCHECK",""+loopi);
    if (loopi < arrayList.size()) {
        getItAgain();
    } else {
        for (String l:weatherInfo) {
            Log.i("LETSCHECK",l); 
            //expected 4 items to show but its showing only 2 items
        }
    }
}

【讨论】:

  • 嗨 Reaz 谢谢你的帮助,让我试试,我会告诉你的
  • 我应该把整个代码转移到 IntentService 类,这样它就不会阻塞整个主 UI
  • 不,它没有阻塞主 UI 线程。这已经是异步的了。让我知道这是否有帮助!
  • 嗨,我已经使用了您的解决方案,效果很好,但是还有另一个问题,请查看我的编辑部分
  • 是的,但是请你看看上面的问题
【解决方案2】:

您正在运行异步代码,并且它们的回调没有一个接一个地返回的原因是合乎逻辑的,因为每个 HTTP 调用都需要一些时间,与其他调用无关,因此实际上可能会收到您的第三个调用的响应在第一个之前。

您可以使用 RxJava(及其运算符),也可以改进当前代码。对于您的startProcess,将 for 循环中的i 作为索引传递,并在我们的函数之外创建一个数组。每当您从服务器获得响应时,您都可以将其存储在数组的ith 位置。每次调用后,您可以检查是否已获取所有值(通过计数器或其他方式)。最好将所有这些东西移到它自己的类中,这样它就可以包含和测试。

需要注意的一点是您将如何处理错误,因为您的呼叫可能无法成功接听。

【讨论】:

  • 感谢您的帮助,如果有效,我会通知您。
【解决方案3】:

这是一个示例代码。每次成功调用后,从数组中删除当前的继续项并执行另一个 API 请求。

private void startProcess(ArrayList<LatLong> elementList){
LatLong myLatlng = elementList.get(0);
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
        .url(myurl)
        .build();
Call call  = httpClient.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {

        String data = response.body().string();
        Log.i("DATASS",data);
        if (response.isSuccessful()){
            try {
                getCurrentDetails(data,myLatlng);
                elementList.remove(0)
                startProcess(elementList)
            }catch (JSONException e){
                e.printStackTrace();
            }


        }
    }

});

}

【讨论】:

  • 嗨,感谢您发布代码,我已经尝试过另一种解决方案,效果很好。
猜你喜欢
  • 1970-01-01
  • 2021-04-07
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2011-10-19
  • 1970-01-01
  • 2014-10-24
相关资源
最近更新 更多