2014-06-23 97 views
2

我知道使用JsonArrayRequest的POST請求不能用於Volley的開箱即用,但是我看到這篇文章here討論了添加構造函數來處理這個問題。他們的實現是這樣的:Android Volley Post Request - JsonArrayRequest的解決方法

public JsonArrayRequest(int method, String url, JSONObject jsonRequest, 
     Listener<JSONArray> listener, ErrorListener errorListener) { 
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), 
     listener, errorListener); 
} 

我該如何去添加這個作爲構造函數?上面的問題提到將其放置在Volley工具庫中。我將Volley作爲一個.jar導入,所以我不確定如何添加這樣的構造函數,或者如果這是最好的方法。任何幫助深表感謝。

編輯

我已經創建了覆蓋和構造下面的類的建議。這裏是類:

public class PostJsonArrayRequest extends JsonArrayRequest { 

    @Override 
    protected Map<String, String> getParams() throws AuthFailureError { 
     HashMap<String, String> params = new HashMap<String, String>(); 
     params.put("name", "value"); 
     return params; 
    } 

    public PostJsonArrayRequest(int method, String url, JSONObject jsonRequest, 
      Listener<JSONArray> listener, ErrorListener errorListener) { 
     super(Method.POST, url, null, listener, errorListener); 
    } 
} 

在排隊叫超我越來越The constructor JsonArrayRequest(int, String, null, Response.Listener<JSONArray>, Response.ErrorListener) is undefined

如何糾正呢?

+0

子類JsonArrayRequest,把構造在那裏,而不是 – panini

回答

2

創建一個類並擴展JsonArrayRequest然後覆蓋

@Override 
protected Map<String, String> getParams() throws AuthFailureError { 
    HashMap<String, String> params = new HashMap<String, String>(); 
    params.put("name", "value"); 
    return params; 
} 

,並添加一個新的構造,並調用它

super(Method.POST, url, null, listener, errorListener); 

或使用此類

public class PostJsonArrayRequest extends JsonRequest<JSONArray> { 

    /** 
    * Creates a new request. 
    * @param url URL to fetch the JSON from 
    * @param listener Listener to receive the JSON response 
    * @param errorListener Error listener, or null to ignore errors. 
    */ 
    public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) { 
     super(Method.POST, url, null, listener, errorListener); 
    } 

    @Override 
    protected Map<String, String> getParams() throws AuthFailureError { 
     HashMap<String, String> params = new HashMap<String, String>(); 
     params.put("name", "value"); 
     return params; 
    } 

    @Override 
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { 
     try { 
      String jsonString = 
        new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 
      return Response.success(new JSONArray(jsonString), 
        HttpHeaderParser.parseCacheHeaders(response)); 
     } catch (UnsupportedEncodingException e) { 
      return Response.error(new ParseError(e)); 
     } catch (JSONException je) { 
      return Response.error(new ParseError(je)); 
     } 
    } 
} 
+0

謝謝你的答案。我創建了一個類來擴展'JsonArrayRequest',爲Map添​​加了覆蓋,並添加了一個像你的例子一樣的構造函數。我用代碼更新了我的問題。我收到一個錯誤(貼在上面)。 – settheline