2015-11-04 41 views
0

我熟悉Volley並創建一個Singleton類,並將請求添加到隊列中。但是,我希望增加排列的模塊性,並簡單地通過方法調用將所有請求調用到另一個類。我已經安裝了本動作作爲基礎用於公共GET請求:無法賦值給最終的Volley變量響應

public Object getRequest(String params) { 

    final JSONObject getRequestReturn = new JSONObject(); 

    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, 
      VolleySingleton.prefixURL, ((String) null), 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 

        // Parse the JSON: 
        try { 
         getRequestReturn = response; 

         Log.v("GET Request value", response.toString()); 

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

       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Log.d("GET Request Error", error.toString()); 
       } 
      }); 

    mRequestQueue.add(getRequest); 

    return getRequestReturn; 
} 

然而,我在有響應的分配一個錯綜複雜的鎖釦22錯誤:

getRequestReturn = response; 

錯誤注意到getRequestReturn必須聲明爲final才能在內部類中使用,但在分配final時,會出現另一個錯誤,指出您無法將值分配給最終變量。

該方法如何處理?

+0

聲明getRequest返回到課程級別 –

+0

不要使用像那樣的回報,你不會得到任何東西,請看看我的答案在下面的問題http://stackoverflow.com/questions/32627089/post-request -json-file-passing-string-and-wait-for-the-response-volley/32627293#32627293 – BNK

+0

另一個http://stackoverflow.com/questions/32375295/android-how-to-return-async-jsonobject -from-method-using-volley :) – BNK

回答

0

將JSONObject聲明爲全局,並在像這樣的相同位置進行初始化。

JSONObject getRequestReturn ; 


getRequestReturn = new JSONObject(); 
0
public Object getRequest(String params) { 

    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, 
      VolleySingleton.prefixURL, ((String) null), 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 

        // Parse the JSON: 
        try { 

         Log.v("GET Request value", response.toString()); 

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

       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Log.d("GET Request Error", error.toString()); 
       } 
      }); 

    mRequestQueue.add(getRequest); 

    return new JSONObject(); 
} 

不能得到的,response當u回報! Volleyrequest是異步!

我用EventBus,我不喜歡這樣寫道:

當我需要從網絡數據,我添加了這樣的請求。

然後,當我從網上獲得響應時,我使用EventBus發佈事件。

我收到活動並更新我的頁面。

或者U可以試用RxAndroid。

+0

這不會輸出任何東西,因爲它只是返回一個新的JSON對象...不是網絡操作輸出的結果 – Sauron

+0

這會在結果來之前返回 –

+0

@Sauron:小小的陽光是對的,你可以參考我上面評論的2個鏈接。 – BNK