-1

i want to get server response during register process, but unfortunately my app keeps crashing here

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

            ServerResponse resp = response.body();
//crash occurs here
            Toast.makeText(getApplicationContext(), resp.getMessage(), Toast.LENGTH_LONG).show();

and this is what logcat says

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.chat.ServerResponse.getMessage()' on a null object reference
                                                              at com.chat.RegisterActivity$3.onResponse(RegisterActivity.java:130)
                                                              at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                              at android.os.Looper.loop(Looper.java:158)

below is my serverResponse class

public class ServerResponse {

private String result;
private String message;
private User user;

public String getResult() {
    return result;
}

public String getMessage() {
    return message;
}

public User getUser() {
    return user;
}
}
Mani
  • 423
  • 1
  • 4
  • 13

3 Answers3

1

Update your method like this:

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

            ServerResponse resp = response.body();

            //check your resp is null or resp.getMessage() is nul here
            if(resp!=null && resp.getMessage() != null)
                Toast.makeText(getApplicationContext(), resp.getMessage(), Toast.LENGTH_LONG).show();

it'll solve your problem.

HassanUsman
  • 1,787
  • 1
  • 20
  • 38
0

The crash might be due to the implementation of Toast, create a separate function for toast then declare it, and it seems that toast is falling in the loop. It results in the crash of app.

0

Make sure that you have created the pojo class like this format..

 public class ServerResponse {

@SerializedName("MESSAGE")
private String MESSAGE;

@SerializedName("MESSAGE")
public void setMESSAGE(String MESSAGE) {
    this.MESSAGE= MESSAGE;
}
@SerializedName("MESSAGE")
public String getMessage() {
    return MESSAGE;
}
}
gStephin
  • 332
  • 3
  • 20