有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使onResponse方法中获得的数据在整个类中可用

基本上,在我的安卓应用程序中,我希望用户搜索世界各地的城市,因此我使用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


共 (1) 个答案

  1. # 1 楼答案

    这就是异步操作的本质,它们不会按照您编写的顺序完成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();
    }