4

I know this is old or repeat question. But I didn't get where am I wrong. I got result null from this JSON.

{
"error": {
    "dateTimeUtc": "2017-12-26T05:46:05.1126801+00:00",
    "errorReference": "sample string 2",
    "errorType": "Error",
    "title": "sample string 3",
    "code": "sample string 4",
    "messages": [
      "sample string 1",
      "sample string 2"
    ]
  },
  "result": {
    "message": "sample string 1"
  }
}

I have this type of JSON to read from Retrofit2. I create one POJO class called RetrofitResponce

private Error error;
private Result result;
public Result getResult ()
{
    return result;
}

public void setResult (Result result)
{
    this.result = result;
}

public Error getError ()
{
    return error;
}

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

@Override
public String toString()
{
    return "ClassPojo [result = "+result+", error = "+error+"]";
}`

Now in call.enque() method to handled response, like

call.enqueue(new Callback<RegisterUser>() {
        @Override
        public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

            try {
                RetrofitResponce retrofitResponce= response.body();

                Error error = retrofitResponce.getError();
                Result result=retrofitResponce.getResult();


                Log.e("Eroor", "rr  " + error.getTitle().toString());
            } catch (Exception e) {

            }
        }

        @Override
        public void onFailure(Call<RetrofitResponce> call, Throwable t) {
            Log.e("Failure ", "fail " + t.toString());
        }
    });

but here I get NullPointerException,i.e. I don't get any response in RestrofitResponce. Error and Result both get Null.

java.lang.NullPointerException: Attempt to invoke virtual method 'net.xyz.abc.Model.Error net.xyz.abc.Model.RegisterUser.getError()' on a null object reference

Please help me. try to solve my query.Thanks in advance.

PostMan responce,

{
"error": {
    "dateTimeUtc": "2017-12-26T07:05:51.1427712Z",
    "errorReference": "00000000-0000-0000-0000-000000000000",
    "errorType": "Error",
    "title": "The request is invalid.",
    "code": null,
    "messages": [
        "Passwords must have at least one non letter or digit character. Passwords must have at least one uppercase ('A'-'Z')."
    ]
},
"result": null

}

RoHiT
  • 372
  • 3
  • 12
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – AskNilesh Dec 26 '17 at 06:28
  • @Rohit, is this the sucess and failure response or sucess response is differ from this? – Chirag Dec 26 '17 at 06:46
  • I tested same URL on PostMan software. I got success there. – RoHiT Dec 26 '17 at 06:48
  • Please post success response and failure both response. – Chirag Dec 26 '17 at 06:49
  • You got null because may be your success response and failure response both are differe. – Chirag Dec 26 '17 at 06:56
  • I think yes,when I check on PostMan I got Result at that time Error is null, n When I got Error at that time Result is null. But I hit URL means response is success. What is solution then? – RoHiT Dec 26 '17 at 06:59
  • You need to add the success and error in one response and make the Response class from that response. – Chirag Dec 26 '17 at 07:38

5 Answers5

3

You have to add the @SerializedName in your Response class for each and every filed same as the web service name.

e.g

@SerializedName("error")
private Error error;
@SerializedName("result")
private Result result;

Please use this website to create your classes from the JSON Response. http://www.jsonschema2pojo.org/

And after that you have to check if response if successful or not.

call.enqueue(new Callback<RegisterUser>() {
        @Override
        public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

            try 
            {
                if(response.isSuccessful() && response.body() != null)
                {
                    RetrofitResponce retrofitResponce= response.body();
                    Error error = retrofitResponce.getError();
                    Result result=retrofitResponce.getResult();
                 }

            } catch (Exception e) {

            }
        }

        @Override
        public void onFailure(Call<RetrofitResponce> call, Throwable t) {
            Log.e("Failure ", "fail " + t.toString());
        }
    });
Chirag
  • 56,621
  • 29
  • 151
  • 198
3

Retrofit callback needs response model, just change this:

call.enqueue(new Callback<RetrofitResponce>() {
        @Override
        public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {


                if (response.isSuccessful()) {
                RetrofitResponce retrofitResponce= response.body();
                if (retrofitResponce!=null) {   
                Error error = retrofitResponce.getError();
                Result result=retrofitResponce.getResult();       
                Log.e("Eroor", "rr  " + error.getTitle().toString());
              }
            }                
        }

        @Override
        public void onFailure(Call<RetrofitResponce> call, Throwable t) {
            Log.e("Failure ", "fail " + t.toString());
        }
    });

Happy coding!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
2

Try this Pojo for RetrofitResponce

public class RetrofitResponce {

@SerializedName("error")
@Expose
private Error error;
@SerializedName("result")
@Expose
private Result result;

public Error getError() {
return error;
}

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

public Result getResult() {
return result;
}

public void setResult(Result result) {
this.result = result;
}

}


public class Result {

@SerializedName("message")
@Expose
private String message;

public String getMessage() {
return message;
}

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

}


public class Error {

@SerializedName("dateTimeUtc")
@Expose
private String dateTimeUtc;
@SerializedName("errorReference")
@Expose
private String errorReference;
@SerializedName("errorType")
@Expose
private String errorType;
@SerializedName("title")
@Expose
private String title;
@SerializedName("code")
@Expose
private String code;
@SerializedName("messages")
@Expose
private List<String> messages = null;

public String getDateTimeUtc() {
return dateTimeUtc;
}

public void setDateTimeUtc(String dateTimeUtc) {
this.dateTimeUtc = dateTimeUtc;
}

public String getErrorReference() {
return errorReference;
}

public void setErrorReference(String errorReference) {
this.errorReference = errorReference;
}

public String getErrorType() {
return errorType;
}

public void setErrorType(String errorType) {
this.errorType = errorType;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public List<String> getMessages() {
return messages;
}

public void setMessages(List<String> messages) {
this.messages = messages;
}

}
Ramesh sambu
  • 3,577
  • 2
  • 24
  • 39
1

I am sure this will help you.

You can not handle Success and Faille by Single model. To get error body you need to call response.errorBody().string()

Try Below Code :

call.enqueue(new Callback<RegisterUser>() {
    @Override
    public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

       try {
                if (response.isSuccessful()) {
                Log.d("Successful",response.body();); 
                } else {
                    Log.d("errorBody ", response.errorBody().string());
                }
            } catch (Exception e) {
                Log.d("Exception ",e.toString());
            }

    }

    @Override
    public void onFailure(Call<RetrofitResponce> call, Throwable t) {
        Log.e("Failure ", "fail " + t.toString());
    }
});
Vishal G. Gohel
  • 1,008
  • 1
  • 16
  • 31
1

Try this.

    call.enqueue(new Callback<RetrofitResponce>() {
    @Override
    public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {

        if (response.body() != null)

       Toast.makeText(YourActivity.this,response.body().getResult(), 
       Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onFailure(Call<RetrofitResponce> call, Throwable t) {
        Log.e("Failure ", "fail " + t.toString());
    }
});
mehul chauhan
  • 1,792
  • 11
  • 26