问题描述
我想处理并在 onErrorResponse中显示一些消息
以下是我的代码。
String url = MainActivity.strHostUrl+"api/delete_picture";
jobjDeleteImage = new JsonObjectRequest(Request.Method.POST, url, jobj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("Image response", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volly Error", error.toString());
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
}
}
});
我想要处理 com.android.volley.TimeoutError
还有一些其他的错误代码,如404,503等,以及 Toast
这里的消息。
I want to handle com.android.volley.TimeoutError
and also some other error code like 404, 503 etc and Toast
message here.
推荐答案
networkResponse为null,因为在TimeoutError中没有从服务器收到数据 - 因此超时。相反,您需要通用客户端字符串来显示其中一个事件。您可以使用instanceof检查VolleyError的类型,以区分错误类型,因为您没有网络响应可以使用 - 例如:
The networkResponse is null because in a TimeoutError no data is received from the server -- hence the timeout. Instead, you need generic client side strings to display when one of these events occur. You can check for the VolleyError's type using instanceof to differentiate between error types since you have no network response to work with -- for example:
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(context,
context.getString(R.string.error_network_timeout),
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
}
这篇关于处理排球错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!