当我应用了使用Valley库的简单代码时,我已经使用了Google示例"/p>
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
message.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
message.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
我得到以下错误。
e/oulley:[77336] networkdispatcher.run:未经手的异常java.lang.nullpointerexception:尝试从null对象参考上读取'int'int java.lang.string.offset' java.lang.nullpoInterException:尝试从null对象参考上的字段" int java.lang.string.offset"读取 在java.lang.string.comparetoignorecase(string.java:560) 在java.lang.string $ caseinsensitivecomparator.compare(string.java:77) 在java.lang.string $ caseinsensitivecomparator.compare(string.java:66) 在java.util.treemap.find(treemap.java:277) 在java.util.treemap.putinternal(treemap.java:240) 在java.util.treemap.put(treemap.java:186) 在com.android.volley.networkresponse.toheadermap(NetworkResponse.java:138) 在com.android.volley.networkresponse。 在com.android.volley.toolbox.basicnetwork.performrequest(basicnetwork.java:169) 在com.android.volley.networkdispatcher.run(NetworkDisPatcher.java:113)
代码说您遇到了NullPointer exception
这意味着您在此代码中使用的变量为null 运行时。
检查您的未零值的通过值。
请参阅此
i经过大量工作,我找到了解决方案,我使用了github的射击图库,而不是使用" compile'com.android.volley.volley:Volley:1.0.0'in应用程序文件的依赖关系。希望是否有人能够更多地解释为什么我无法使用Github中的库。谢谢大家的帮助。
请从响应中删除子字符串: -
message.setText("Response is: "+ response.substring(0,500));
更改后:
if(response.lemght>500){
message.setText("Response is: "+ response.substring(0,500));
}else{
message.setText("Response is: "+ response);
}
尝试这个创建请求时,请通过上下文而不是getApplicationContext(): -
RequestQueue queue = Volley.newRequestQueue(this);//if you are in activity, if you are in fragment then **getActivity()**
在您进行网络调用时,您可能会获得成功,但有时不会获得数据。因此,请确保在访问数据之前进行零检查。
if(response!=null){
message.setText("Response is: "+ response.substring(0,500));
}