3

下面是一個我試圖通過調用getSelf()來檢索用戶對象的方法。問題在於結果始終爲空,因爲Volley請求在返回結果時尚未完成。我對於異步流程有點新,所以我不確定讓方法等待API調用的結果返回UserBean對象的最佳方式。任何人都可以給我一些幫助嗎?等待Async Volley請求的結果並返回它

public UserBean getSelf(String url){ 

    RpcJSONObject jsonRequest = new RpcJSONObject("getSelf", new JSONArray()); 

    JsonObjectRequest userRequest = new JsonObjectRequest(Request.Method.POST, url, jsonRequest, 
     new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 

       String result; 
       try { 
        result = response.getString("result"); 
        Gson gson = new Gson(); 
        java.lang.reflect.Type listType = new TypeToken<UserBean>() {}.getType(); 

        //HOW DO I RETURN THIS VALUE VIA THE PARENT METHOD?? 
        userBean = (UserBean) gson.fromJson(result, listType); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 

      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.e("Error:", error.toString()); 
       finish(); 
      } 
     } 
    ); 

    this.queue.add(userRequest); 


    return userBean; 

} 
+0

你不應該做你想做的事情。異步處理的原因是,在做「慢」的事情時你不會阻止程序或用戶界面。所以你的'onResponse'應該通知調用者該對象可用,然後顯示它。如果您需要用戶等待,請提出進度對話框,然後在結果可用時將其解除。 – 323go

+0

也檢查你的迴應。它可能是'null'。 –

回答

0

爲此,可以使用該庫VolleyPlus https://github.com/DWorkS/VolleyPlus

它有一種叫做VolleyTickle和RequestTickle實現。請求是一樣的。它是同步請求,並且只有一個請求。

+1

我認爲在** VolleyPlus:**如果緩存發現它從緩存中取回並回應到UI主線程。它使我成爲問題,因爲如果更新JSON,它不會更新數據。任何解決這個問題的方法? –

+0

您可以在請求中使用setShouldCache方法。將false傳遞給該方法,並且不會緩存結果。 – 1HaKr

9

對於那些從搜索到這個問題&谷歌。

沒有理由等待異步請求完成,因爲它在設計上是異步的。如果你想用亂射,實現同步的行爲,你必須使用所謂的期貨

String url = "http://www.google.com/humans.txt"; 

RequestFuture<String> future = RequestFuture.newFuture(); 
StringRequest request = new StringRequest(Request.Method.GET, url, future, future) 
mRequestQueue.add(request); 

String result = future.get(); // this line will block 

請記住,你必須運行在另一個線程阻塞代碼,因此它包裝成AsyncTask(否則future.get()將永遠阻止)。