【发布时间】:2018-09-20 09:04:35
【问题描述】:
我正在使用 Retrofit 与 Android 上的 REST API 进行通信,但我 得到如下所示的 NullPointerException。我尝试使用邮递员, API 工作正常,我得到登录正常工作的响应。
错误
进程:com.example.krish.webdemo,PID:3064 java.lang.NullPointerException 在 com.example.krish.webdemo.activities.LoginActivity$2.onResponse
Call<LoginResponse> call = RetrofitClient
.getInstance()
.getApi()
.userLogin(email, password);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
if (!loginResponse.isError()) {
Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
}
});
}
我的登录响应中有一个NullPointerException,'.isError()' 是
显示空错误
API 接口
@FormUrlEncoded
@POST("userlogin")
Call<LoginResponse> userLogin(
@Field("email") String email,
@Field("password") String password
);
改造实例
private static final String BASE_URL ="http://192.168.1.38/KrishApi/public/";
private static RetrofitClient mInstance;
private Retrofit retrofit;
private RetrofitClient() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance() {
if (mInstance == null) {
mInstance = new RetrofitClient();
}
return mInstance;
}
public Api getApi(){
return retrofit.create(Api.class);
}
JSON 响应
{
"error": false,
"message": "Login Successful",
"user": {
"id": 3,
"email": "pandi@gmail.com",
"name": "pandi",
"age": "22",
"college": "sec"
}
}
POJO 类
public class LoginResponse {
private boolean error;
private String message;
private User user;
public LoginResponse(boolean error, String message, User user) {
this.error = error;
this.message = message;
this.user = user;
}
public boolean isError() {
return error;
}
public String getMessage() {
return message;
}
public User getUser() {
return user;
}
}
【问题讨论】:
标签: android retrofit2 android-developer-api