应用程序在resp.getMessage()调用时崩溃

时间:2017-11-01 04:21:23

标签: android web-services response

我希望在注册过程中获得服务器响应,但不幸的是我的应用程序一直在崩溃

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

这就是logcat所说的

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)

下面是我的serverResponse类

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

3 个答案:

答案 0 :(得分:1)

更新 方法,如下所示:

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

它会解决你的问题。

答案 1 :(得分:0)

崩溃可能是由于Toast的实现,为toast创建一个单独的函数然后声明它,并且似乎toast正在循环中。它导致应用程序崩溃。

答案 2 :(得分:0)

确保您已创建类似此格式的pojo类。

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