krishna
krishna

Reputation: 21

NullPointerException using Retrofit response

I'm using Retrofit to communicate with REST API on Android, but I'm getting a NullPointerException like below. I try using Postman, the API is working fine and I get the response the login was working.

Error

Process: 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) {

            }
        });
    }

I had a NullPointerException to my loginResponse, the '.isError()' was showing null error

API interface

@FormUrlEncoded
    @POST("userlogin")
    Call<LoginResponse> userLogin(
            @Field("email") String email,
            @Field("password") String password
    );

Retrofit instance

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 response

{
    "error": false,
    "message": "Login Successful",
    "user": {
        "id": 3,
        "email": "[email protected]",
        "name": "pandi",
        "age": "22",
        "college": "sec"
    }
}

POJO class

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

Upvotes: 1

Views: 3426

Answers (2)

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75778

"error": false,

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

You should check your response isSuccess() or not.

/** {@code true} if {@link #code()} is in the range [200..300). */
public boolean isSuccess() { return rawResponse.isSuccessful(); }

              if (response.isSuccess()) //isSuccessful()
                {
                   LoginResponse loginResponse = response.body();
                    ////
                }

Upvotes: 1

Nabin Bhandari
Nabin Bhandari

Reputation: 16379

response.body() returns null if the response is not successful. So, you must always check if the response is successful or not inside the onResponse method.

    @Override
    public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

        if (response.isSuccessful()){
            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();
            }

        } else{
             ResponseBody errorBody = response.errorBody();
             // check error.
        }
    }

Upvotes: 1

Related Questions