api – Android NullPointerException in Retrofit response-ThrowExceptions

Exception or error:

In my activity I have more than one Retrofit services operations and these services relay on same Retrofit Callback methods. And these causes null pointer when one service try to get a callback at the same time callback is used by other service, how to fix this problem?

I have been using retrofit for my webservice calls. It is working fine in emulator but when I use a real device it crashes and got the error log as:

  java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
    at com.itmam.info.jadara.Notifications.Notifications_Items_Adapter$4.onResponse(Notifications_Items_Adapter.java:309)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8147)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)

This is my Retrofit client class:

public class RetrofitGeneral {

private static Retrofit retrofit;
private static final String BASE_URL = "My_URL";

public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
 }
}

This is my Retrofit Service interface:

public interface getClientDetails {
@FormUrlEncoded
@POST("WebService.asmx/SelectClientById")
Call<List<ClientDetails>> getClientdetails(
        @Field("ClientID") int ClientID,
        @Field("Token") String Token,
        @Field("CurrentEmployeeID") int CurrentEmployeeID
 );
}

And this way i am making a call to Retrofit service from my adapter onBindViewHolder that call the retrofit more than one time:

@Override
public void onBindViewHolder(Notifications_Items_Adapter.Notifications_Holder holder, int position) {
    myHolder = holder;
    holderList.add(holder);
    getTaskId(position);
    getTaskDetails(taskID);

}

This is my retrofit callBack method:

private void getTaskDetails(int taskID){
    getTaskDetails getTaskDetails=RetrofitGeneral.getRetrofitInstance().create(getTaskDetails.class);
    Call<List<Task>> listCall=getTaskDetails.getDetails(taskID,Log_in.getToken(),Log_in.CurrentEmployeeID);
    listCall.enqueue(new Callback<List<Task>>(){
        @Override
        public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
            task = response.body().get(0); // Error here after the second call. 
            tasksList.add(task);
        }

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

        }
    });
}

Please help 🙂

How to solve:

public void onResponse(Call call, Response response) {

if (response.isSuccessful()) {

Log.e(TAG, “onResponse: calling”);

if (response.body().getStatus_code() == 200) {

Log.e(TAG, “onResponse: calling 200”);

            }

        } else {
            Log.e(TAG, "onResponse: else--");
            if (response.code() == 500) {
                Log.e(TAG, "onResponse: 500");

                //and if you want to parse your error body try this

                /*
                try {
                    Gson gson = new Gson();
                    YourErrorClass error = gson.fromJson(response.errorBody().charStream(), YourErrorClass.class);

                } catch (Exception e) {
                     Log.e(TAG, "onResponse error: " + e.getMessage());
                }*/



            } else if (response.code() == 406) {
                Log.e(TAG, "onResponse: 406");
            } else {
                Log.e(TAG, "onResponse: esle");
            }

        }

    }

###

The error is because of this line

Toast.makeText(context, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();

listCall.enqueue makes the network call on background Thread and you can’t display a toast from background thread, you have to use Main thread to display a toast.

You can use

runOnUiThread(new Runnable() {
Toast.makeText(context, "Something went wrong...Please try later!",Toast.LENGTH_SHORT).show();
}

To fix the error.

For the answer why your call is failing you can print the stacktrace to figure that out

 @Override
    public void onFailure(Call<List<Task>> call, Throwable t) {
        t.printStackTrace();
        runOnUiThread(new Runnable() {
        Toast.makeText(context, "Something went wrong...Please try later!",Toast.LENGTH_SHORT).show();
       }
    }

###

The problem was fixed by using Retrofit Synchronous like that :

UserService service = ServiceGenerator.createService(UserService.class);

// 1. Calling '/api/users/2' - synchronously

Call<UserApiResponse> callSync = service.getUser(2);

try
{
  Response<UserApiResponse> response = callSync.execute();
  UserApiResponse apiResponse = response.body();

  //API response
  System.out.println(apiResponse);
} 
catch (Exception ex) 
{ 
  ex.printStackTrace();
}

from Retrofit 2 – Synchronous and asynchronous call example.

Leave a Reply

Your email address will not be published. Required fields are marked *