Я использую Retrofit для связи с REST API на Android, но я получаю исключение NullPointerException, как показано ниже.Я пытаюсь использовать Postman, API работает нормально, и я получаю ответ, что вход в систему работал.
Ошибка
Процесс: com.example.krish.webdemo, PID: 3064 java.lang.NullPointerException at 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
для моего логинаResponse, '.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;
}
}