0
基本上在我的Android應用我想用戶搜索世界各地的城市,所以我使用的API來獲取世界上所有的城市和一個ArrayList
存儲,這有在okhttp庫的onResponse
方法中完成,之後該列表變爲空。此數組列表僅保存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
。
精彩..它工作..感謝一噸。 –