Priya Priya - 3 years ago 151
Android Question

getting response 404 and app crash retrofit

I am trying to implement retrofit for get and store advertise related int value in my android application. I am getting response like

{"banner_on":"1","int_on":"1","int_click":"3"}
from API.

I am using code in splash screen like this

Retrofit retrofit = ApiClient.getClient();
ApiService apiService = retrofit.create(ApiService.class);
apiService.getads().enqueue(new Callback<Ads>() {
@Override
public void onResponse(Call<Ads> call, Response<Ads> response) {

constant.banner_on = response.body().banner_on();
constant.int_on = response.body().int_on();
constant.int_click = response.body().int_click();

}

@Override
public void onFailure(Call<Ads> call, Throwable t) {

}
});


My Ads Model is like below

public final class Ads {
@SerializedName("success")

private int banner_on;
private int int_on;
private int int_click;

public int banner_on() {
return banner_on;
}
public int int_on() {
return int_on;
}
public int int_click() {
return int_click;
}
}


and my ApiService is like below

@GET("getads.php")
Call<Ads>getads();


I am getting error like below

java.lang.NullPointerException: Attempt to invoke virtual method 'int com.myapp.example.model.Ads.banner_on()' on a null object reference


Let me know if someone can correct me where I am wrong.
Thanks

Answer Source

The response.body() will be null if the request is unsuccessful.

if(response.isSuccessful()) //use response.body();
else // use response.errorBody();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download