2016-12-10 61 views
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

回答

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(); 
} 
+0

精彩..它工作..感謝一噸。 –

相關問題