保持在onResponse方法中获得的数据在整个班级中都可用

时间:2016-12-10 00:35:10

标签: java android json response okhttp3

基本上在我的Android应用程序中我希望用户搜索世界各地的城市,因此我使用api来获取世界上所有城市并存储在ArrayList中,这已经在{{{ 1}} 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的技巧。

1 个答案:

答案 0 :(得分:1)

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