2016-01-12 56 views
4

我是新來的谷歌的排球網絡庫(也是Android!),我試圖以動態的方式傳遞POST參數!Android凌空,如何動態傳遞發佈參數

現在我正在使用getParams()方法: 並以硬編碼的方式返回params。

@Override 
protected Map<String, String> getParams() 
{ 
     Map<String, String> params = new HashMap<String, String>(); 
     params.put("login", "my_login"); 
     params.put("password", "my_password"); 
     return params; 
} 

我想傳遞變量,而不是「硬編碼」串...

首先,我試圖把我的地圖則params的是我的類的成員,但類成員都沒有可用getParams()方法。

也許我可以使用單例類來讓我可以給我想要傳遞的參數,並使用getParams()方法中的實例返回它們?但我認爲這不是正確的方式。

下面是我的截擊要求的孔代碼:

RequestQueue queue = VolleySingleton.getInstance().getRequestQueue(); 

String url = "https://theUrlToRequest"; 

StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
        new Response.Listener<String>() 
        { 
         @Override 
         public void onResponse(String response) { 
          JSONObject mainObject = null; 
          try { 
           Log.i("app", "Result = " + response); 
          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 

         } 
        }, 
        new Response.ErrorListener() 
        { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          Log.i("app", "Fail on Login" + error.toString()); 
         } 
        } 
      ) { 
       @Override 
       protected Map<String, String> getParams() 
       { 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("login", "my_login"); 
        params.put("password", "my_password"); 

        return params; 
       } 
      }; 

queue.add(postRequest); 
+0

爲什麼不創建一些變量並在請求之前將它們均衡爲類變量,並添加您爲params創建的變量? – shanks

+0

它必須從'getParams()'返回'Map ',而不是隻在那裏定義它。您可以創建自己的集合作爲類級別的變量,並從'getParams()'中返回。 – astuter

+0

@ k::這是一個很好的理想。我會立即嘗試。謝謝。 – Doctor

回答

1

在這種情況下,你可以創建一個類擴展StringRequest。添加一個attr來存儲參數並將其返回到getParams();

MyStringRequest extends StringRequest{ 

    private Map params = new HashMap(); 
    public MyStringRequest (Map params,int mehotd,String url,Listener listenr,ErrorListener errorListenr){ 
    super(mehotd,url,listenr,errorListenr) 

     this.params = params 

    } 
    @Override 
    protected Map<String, String> getParams(){ 

     return params; 

    } 

} 

RequestQueue queue = VolleySingleton.getInstance().getRequestQueue(); 

String url = "https://theUrlToRequest"; 
Map<String, String> params = new HashMap<String, String>(); 
params.put("login", "my_login"); 
params.put("password", "my_password"); 
MyStringRequest postRequest = new MyStringRequest (params ,Request.Method.POST, url, 
    new Response.Listener<String>(){ 
    }, 
    new Response.ErrorListener(){ 
    } 
); 
queue.add(postRequest); 
+0

謝謝!添加其他類「MyStringRequest」是完美的....! – Doctor