保持在 onResponse 方法中获得的数据在整个 class 期间可用

keep data obtained in onResponse method available throughout the class

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

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 中,在填充 allCities --

之后调用 updateUI(或任何你称之为的东西)
@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();
}