Dinesh
Dinesh

Reputation: 71

Error handling using volley in android

I want to print my Error from onErrorResponse using volley in android, i want to print them separately in different textview.

my error from onErrorResponse

{
    "message": "422 Unprocessable Entity",
    "error": {

      "username": [
            "The username has already been taken."
        ],
        "email": [
            "The email has already been taken."
        ]
    },
    "status_code": 422
}

so i want to print them separately, i mean The username has already been taken. in one textview and The email has already been taken. in 2nd textview. thank

My Code:

public void postData(JSONObject jsonObject) {       
    String url = "http://www.xxxxxxxx.com/api/v1/auth/register";
    String REQUEST_TAG = "volley_key";      
    JsonObjectRequest jsonObjectReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        verifyResponse(response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {            
            NetworkResponse networkResponse = error.networkResponse;
            if (networkResponse != null && networkResponse.data != null) {
                String errorStr = new String(networkResponse.data);                  
                try {
                    JSONObject jObj = new JSONObject(errorStr);
                    JSONObject objError = jObj.getJSONObject("error");
                    JSONArray emailArray = objError.getJSONArray("email");
                    if (emailArray != null) {
                        String emailMessage = String.valueOf(emailArray.get(0));
                        Toast.makeText(getApplication(), emailMessage, Toast.LENGTH_LONG).show();
                    }
                    JSONArray usernameArray = objError.getJSONArray("username");
                    if (usernameArray != null) {
                        String usernameMessage = String.valueOf(emailArray.get(0));
                        Toast.makeText(getApplication(), usernameMessage, Toast.LENGTH_LONG).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }){
        @Override
        protected VolleyError parseNetworkError(VolleyError volleyError) {

            if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
                VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
                volleyError = error;
            }
            return volleyError;
        }
    };      VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectReq, REQUEST_TAG);
}

Upvotes: 0

Views: 1012

Answers (2)

Chandan Bhandari
Chandan Bhandari

Reputation: 217

you can check for the keys inside error object and simply can check if the key exists then show the error for particular Textview. here is the example.I am taking a case where you are using JsonObject class of volley i.e, the response is in JsonObject.

JsonObject obj=response.getAsJsonObject("error");
if(obj.has("name")){
    nameTextView.setText(obj.getAsJsonArray("name").get(0)+"");
}
if(obj.has("username")){
    usernameTextView.setText(obj.getAsJsonArray("username").get(0)+"");
}
if(obj.has("email")){
    emailTextView.setText(obj.getAsJsonArray("email").get(0)+"");
}

Upvotes: 0

Jeevan Deshmukh
Jeevan Deshmukh

Reputation: 39

Add there ErrorModel.class and Error class into java folder.

package co.exmaple;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ErrorModel {

    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("error")
    @Expose
    private Error error;
    @SerializedName("status_code")
    @Expose
    private Integer statusCode;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Error getError() {
        return error;
    }

    public void setError(Error error) {
        this.error = error;
    }

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

}

Erro.class

package co.exmaple;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Error {

    @SerializedName("name")
    @Expose
    private List<String> name = null;
    @SerializedName("username")
    @Expose
    private List<String> username = null;
    @SerializedName("email")
    @Expose
    private List<String> email = null;

    public List<String> getName() {
        return name;
    }

    public void setName(List<String> name) {
        this.name = name;
    }

    public List<String> getUsername() {
        return username;
    }

    public void setUsername(List<String> username) {
        this.username = username;
    }

    public List<String> getEmail() {
        return email;
    }

    public void setEmail(List<String> email) {
        this.email = email;
    }

}

Then in StringError Request set Error text into texView.

StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {



            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
 GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                ErrorModel error = gson.fromJson(response,ErrorModel.class);
                recyclerView.setAdapter(new ErrorAdapter(ErrorActivity.this,error.getError));
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

Make RecyclerView adapter to set Error text to TextView

Upvotes: 1

Related Questions