gpt4 book ai didi

android - 将具有空值的字符串作为参数传递时, Volley 字符串请求错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:06:34 25 4
gpt4 key购买 nike

我正在使用以下代码进行 volley 的字符串请求

    pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
StringRequest strReq = new StringRequest(Method.POST,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pDialog.dismiss();
Log.e(tag, response);
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
}

}) {

protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "SHOW_FILE");
params.put("filename",filename);
return params;
};

};
// Adding request to request queue
Application.getInstance().addToRequestQueue(strReq, "get_file");

如果变量 filename=null,我会收到以下错误:

08-02 10:28:06.192: E/Volley(2935): [2128] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException
08-02 10:28:06.192: E/Volley(2935): java.lang.NullPointerException
08-02 10:28:06.192: E/Volley(2935): at libcore.net.UriCodec.encode(UriCodec.java:132)
08-02 10:28:06.192: E/Volley(2935): at java.net.URLEncoder.encode(URLEncoder.java:57)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.Request.encodeParameters(Request.java:449)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.Request.getBody(Request.java:435)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:93)
08-02 10:28:06.192: E/Volley(2935): at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)

是否需要对我发布的所有参数进行空值检查或任何其他方法来解决此问题并使用 NULL 值进行处理?

最佳答案

感谢 Giru Bhai 的帮助

我创建了一个新方法来解决变量变为空的问题

       protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("key1", value1);
params.put("key2",value2);
params.put("key3",value3);
return checkParams(params);
};


private Map<String, String> checkParams(Map<String, String> map){
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
if(pairs.getValue()==null){
map.put(pairs.getKey(), "");
}
}
return map;
}

我认为这比在将其放入 map 之前检查每个值更容易

关于android - 将具有空值的字符串作为参数传递时, Volley 字符串请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25091913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com