Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

android - Handle Volley error

I want to handle and show some message in onErrorResponse

below is my code.

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));
        }
    }
});

I want to handle com.android.volley.TimeoutError and also some other error code like 404, 503 etc and Toast message here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...