0

這裏的情況,我有2個類,我的片段和一個單獨的類來獲取我的對象。每次創建這個片段時,它都會要求我的單例使用Volley從我的服務器使用JSON創建對象。但是,這導致我的單例在完全創建之前返回對象。這意味着我的片段不會顯示任何內容,除非某些情況下HTTP請求首先完成。 (我嘗試了日誌記錄,而且方法調用的順序並不正確)
什麼是好方法,以便在所有HTTP請求完成後更新視圖? (我想傳遞片段的對象到我廠,並要求我的片段的方法onResponse的,但我想它會變得混亂,如果我需要我的其他類廠?)在處理併發機器人凌空

public class myFragment extends Fragment{ 
    onCreate(){ 
     ... 
     UpdateUI(); 
    } 

    private void updateUI(){ 
     Factory factory = factory.get(getActivity()); 
     things = pabrik.getThings(); 
     ... 
    } 
} 

public class Factory{ 
    Factory factory; 
    List<Things> things; 

    private Factory(Context c){ 
     things = new ArrayList<>(); 
     JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "10.0.2.2/...", null, 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        try { 
         JSONArray arr = response.getJSONArray("user"); 
         for (int i = 0; i < arr.length(); i++){ 
          things.add(new Barang(arr.getJSONObject(i).getString("email"), i)); 
          Log.d("GET", arr.getJSONObject(i).getString("email")); 
         } 
        }catch (JSONException e){ 
         e.printStackTrace(); 
        } 

       } 
      }, 
     ... 
     ); 
     mRequestQ.add(request); 
    } 

    public static synchronized Factory get(Context c){ 
     if(this.factory == null){ 
      this.factory = new Factory(c); 
     } 
     return this.factory;   
    } 

    public List<Things> getThings(){ 
     return this.Things; 
    } 
} 

回答

1

凌空的主要用例是從主(事件)線程進行聯網。因此,在主線程的onResponse方法中,不管你在單例中做什麼。 Volley確保網絡任務在單獨的後臺線程上運行,並在後臺完成執行後調用onResponse。

public class myFragment extends Fragment{ 
onCreate(){ 
    ... 
    UpdateUI(); 
} 

private void updateUI(){ 
    Factory factory = factory.get(getActivity()); 
    things = new ArrayList<>(); 
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "10.0.2.2/...", null, 
     new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       try { 
        JSONArray arr = response.getJSONArray("user"); 
        for (int i = 0; i < arr.length(); i++){ 
         things.add(new Barang(arr.getJSONObject(i).getString("email"), i)); 
         Log.d("GET", arr.getJSONObject(i).getString("email")); 
         //Update ListView or do something with the data 
        } 
       }catch (JSONException e){ 
        e.printStackTrace(); 
       } 

      } 
     }, 
    ... 
    ); 
    mRequestQ.add(request); 
    ... 
} 

}

PS: 如果你想使用一個單身,你應該通過一個監聽器接口,並處理程序和活套的工作。 Handler在後臺線程中執行任務,然後通過實現接口的對象更新主線程。凌空的目的是爲了避免這些併發症。

+0

@Rei:請問您可以註冊嗎?) – Srinivas