基本上在我的Android应用程序中,我希望用户搜索世界各地的城市,因此我正在使用api获取世界上所有的城市并存储在ArrayList中,这是通过okhttp库的onResponse方法完成的然后列表变为空。该数组列表仅在onResponse中保存值,但是我想在执行后在整个类中使用它。有人可以给我任何想法吗?这是代码。

onCreate(){
OkHttpClient client = new OkHttpClient();
    final Request request = new Request.Builder()
            .url("https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json")
            .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                fullObject = new JSONObject(response.body().string());
                JSONArray s = fullObject.names();
                for(int i=0; i<s.length(); i++) {
                    JSONArray citiesOfOneCoutry = null;
                    citiesOfOneCoutry = fullObject.getJSONArray(s.getString(i));
                    for(int j=0; j<citiesOfOneCoutry.length();j++) {
                        allCities.add(citiesOfOneCoutry.getString(j));
                    }
                    Log.d(TAG, "onResponse: in for "+allCities.size());
                }
                Log.d(TAG, "onResponse: outside for "+allCities.size()); //gives full size.
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "onResponse: outside try "+allCities.size()); //gives full size
        }
    });

    Log.d(TAG, "outside response inside oncreate"+allCities.size()); //gives 0


}

我在日志中看到,来自onResponse外部的消息是第一个,然后执行回调。这是完全可以理解的,但是我想要在响应执行后获得此ArrayList的技巧。

最佳答案

这就是异步操作的本质,它们不按照您编写它们的顺序完成。 allCities数据在您的onCreate方法中将不可用,因为它还没有执行的机会。在onResponse之外使用它的技巧是将依赖于响应的代码移至其自己的方法。

private void updateUI() {
     // Your code that relies on 'allCities'
}


然后在onResponse中,在填充updateUI后调用allCities(或任何您称呼的名称)-

@Override
public void onResponse(Response response) throws IOException {
    try {
        fullObject = new JSONObject(response.body().string());
        JSONArray s = fullObject.names();
        for(int i=0; i<s.length(); i++) {
            JSONArray citiesOfOneCoutry = null;
            citiesOfOneCoutry = fullObject.getJSONArray(s.getString(i));
            for(int j=0; j<citiesOfOneCoutry.length();j++) {
                allCities.add(citiesOfOneCoutry.getString(j));
            }
            Log.d(TAG, "onResponse: in for "+allCities.size());
        }
        Log.d(TAG, "onResponse: outside for "+allCities.size()); //gives full size.
    } catch (JSONException e) {
         e.printStackTrace();
    }
    Log.d(TAG, "onResponse: outside try "+allCities.size()); //gives full size
    updateUI();
}

关于java - 保持在整个类中可用onResponse方法获得的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41070937/

10-10 17:09