RecyclerView adapter's getItemCount throws NullPointerException

In my project, I am fetching data from a server and displaying it in a Recyclerview. After adding data to a list and calling it in getItemCount(), I get null and it throws an exception.

public class AppointmentResponse {
    private static final String TAG = "Appointment Response";
    @SerializedName("data")
    @Expose
    private List<AppntRespData> data = null;
    @SerializedName("error_code")
    @Expose
    private String errorCode;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("status")
    @Expose
    private String status;

    public List<AppntRespData> getData() {
        return data;
    }

    public AppointmentResponse() {
    }

    public AppointmentResponse(List<AppntRespData> data, String errorCode, String message, String status) {
        this.data = data;
        this.errorCode = errorCode;
        this.message = message;
        this.status = status;
    }

    public void setData(List<AppntRespData> data) {
        this.data = data;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "AppointmentResponse{" +
            "data=" + data +
            ", errorCode='" + errorCode + '\'' +
            ", message='" + message + '\'' +
            ", status='" + status + '\'' +
            '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AppointmentResponse that = (AppointmentResponse) o;

        if (data != null ? !data.equals(that.data) : that.data != null) return false;
        if (errorCode != null ? !errorCode.equals(that.errorCode) : that.errorCode != null)
            return false;
        if (message != null ? !message.equals(that.message) : that.message != null) return false;
    return status != null ? status.equals(that.status) : that.status == null;

    }

    @Override
    public int hashCode() {
        int result = data != null ? data.hashCode() : 0;
        result = 31 * result + (errorCode != null ? errorCode.hashCode() : 0);
        result = 31 * result + (message != null ? message.hashCode() : 0);
        result = 31 * result + (status != null ? status.hashCode() : 0);
        return result;
    }

public static class AppntRespData
{
    @SerializedName("with_whom")
    @Expose
    private String withWhom;
    @SerializedName("service_type")
    @Expose
    private String serviceType;
    @SerializedName("appointment_time")
    @Expose
    private String appointmentTime;
    @SerializedName("appointment_status")
    @Expose
    private String appointmentStatus;
    @SerializedName("appointment_id")
    @Expose
    private String appointmentId;
    @SerializedName("appointment_date")
    @Expose
    private String appointmentDate;

    public AppntRespData() {
    }

    public AppntRespData(String withWhom, String serviceType, String appointmentTime, String appointmentStatus, String appointmentId, String appointmentDate) {
        this.withWhom = withWhom;
        this.serviceType = serviceType;
        this.appointmentTime = appointmentTime;
        this.appointmentStatus = appointmentStatus;
        this.appointmentId = appointmentId;
        this.appointmentDate = appointmentDate;
    }

    public String getWithWhom() {
        return withWhom;
    }

    public void setWithWhom(String withWhom) {
        this.withWhom = withWhom;
    }

    public String getServiceType() {
        return serviceType;
    }

    public void setServiceType(String serviceType) {
        this.serviceType = serviceType;
    }

    public String getAppointmentTime() {
        return appointmentTime;
    }

    public void setAppointmentTime(String appointmentTime) {
        this.appointmentTime = appointmentTime;
    }

    public String getAppointmentStatus() {
        return appointmentStatus;
    }

    public void setAppointmentStatus(String appointmentStatus) {
        this.appointmentStatus = appointmentStatus;
    }

    public String getAppointmentId() {
        return appointmentId;
    }

    public void setAppointmentId(String appointmentId) {
        this.appointmentId = appointmentId;
    }

    public String getAppointmentDate() {
        return appointmentDate;
    }

    public void setAppointmentDate(String appointmentDate) {
        this.appointmentDate = appointmentDate;
    }

    @Override
    public String toString() {
        return "AppntRespData{" +
                "withWhom='" + withWhom + '\'' +
                ", serviceType='" + serviceType + '\'' +
                ", appointmentTime='" + appointmentTime + '\'' +
                ", appointmentStatus='" + appointmentStatus + '\'' +
                ", appointmentId='" + appointmentId + '\'' +
                ", appointmentDate='" + appointmentDate + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AppntRespData that = (AppntRespData) o;

        if (withWhom != null ? !withWhom.equals(that.withWhom) : that.withWhom != null)
            return false;
        if (serviceType != null ? !serviceType.equals(that.serviceType) : that.serviceType != null)
            return false;
        if (appointmentTime != null ? !appointmentTime.equals(that.appointmentTime) : that.appointmentTime != null)
            return false;
        if (appointmentStatus != null ? !appointmentStatus.equals(that.appointmentStatus) : that.appointmentStatus != null)
            return false;
        if (appointmentId != null ? !appointmentId.equals(that.appointmentId) : that.appointmentId != null)
            return false;
        return appointmentDate != null ? appointmentDate.equals(that.appointmentDate) : that.appointmentDate == null;

    }

    @Override
    public int hashCode() {
        int result = withWhom != null ? withWhom.hashCode() : 0;
        result = 31 * result + (serviceType != null ? serviceType.hashCode() : 0);
        result = 31 * result + (appointmentTime != null ? appointmentTime.hashCode() : 0);
        result = 31 * result + (appointmentStatus != null ? appointmentStatus.hashCode() : 0);
        result = 31 * result + (appointmentId != null ? appointmentId.hashCode() : 0);
        result = 31 * result + (appointmentDate != null ? appointmentDate.hashCode() : 0);
        return result;
    }
}
}

My JSON data fetching method

 ApiInterface service = RestClient.getApiInterface();

    final Call<AppointmentResponse> AppResp = service.postAppointListData(appntRequest);

    AppResp.enqueue(new Callback<AppointmentResponse>() {
        @Override
        public void onResponse(@NonNull Call<AppointmentResponse> call, @NonNull Response<AppointmentResponse> response) {

            try {
                if (response.body().getErrorCode().equals("0")) {

                    AppointmentResponse.AppntRespData mAppData = new AppointmentResponse.AppntRespData();


                    for (int i=0;i<response.body().getData().size();i++) {


                        mAppData.setWithWhom(response.body().getData().get(i).getWithWhom());
                        mAppData.setAppointmentDate(response.body().getData().get(i).getAppointmentDate());
                        mAppData.setAppointmentId(response.body().getData().get(i).getAppointmentId());
                        mAppData.setAppointmentStatus(response.body().getData().get(i).getAppointmentStatus());
                        mAppData.setAppointmentTime(response.body().getData().get(i).getAppointmentTime());
                        mAppData.setServiceType(response.body().getData().get(i).getServiceType());

                 //public ArrayList<AppointmentResponse.AppntRespData> appointmentlist;

                        appointmentlist.add(mAppData);


                    }


                    Log.d(TAG, "onResponse: appointList--"+appointmentlist);



                }

                else {
                    Toast.makeText(getContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();;
                }
            }catch (Exception e)
            {
                e.getMessage();
            }
        }

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

            t.getMessage();

        }
    });

My Recycler Adapter class

public class AppointRecycleAdapter extends RecyclerView.Adapter<AppointRecycleAdapter.AppointViewHolder> {
    private Context mContext;
    private ArrayList<AppointmentResponse.AppntRespData> appointmentlist;
    private static final String TAG = "AppointRecycleAdapter";

    public AppointRecycleAdapter(Context mContext, ArrayList<AppointmentResponse.AppntRespData> appointmentlist) {
        this.mContext = mContext;
        this.appointmentlist = appointmentlist;
    }

    public class AppointViewHolder extends RecyclerView.ViewHolder {
        private CardView mCradview;
        private TextView tvInsWith,tvInsApDate,tvInsApStatus;

        public AppointViewHolder(View itemView) {
            super(itemView);

            mCradview = itemView.findViewById(R.id.cardViewAppnt);
            tvInsApDate = itemView.findViewById(R.id.InsAppntDate);
            tvInsApStatus = itemView.findViewById(R.id.InsAppntStatus);
            tvInsWith = itemView.findViewById(R.id.Inswith);
        }
    }



    @Override
    public AppointViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.appointmentcardlayout,parent,false);
        return new AppointViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(AppointViewHolder holder, int position) {
        Log.d(TAG, "onBindViewHolder: in");
       //final AppointmentResponse.AppntRespData bean = appointmentlist.get(position);

         holder.tvInsApStatus.setText(appointmentlist.get(position).getAppointmentStatus());
      //holder.tvInsWith.setText(appointmentResponseList.get(position).getWithWhom());
    //holder.tvInsApDate.setText(bean.getAppointmentDate());
  //  holder.tvInsApStatus.setText(appointmentResponseList.get(position).getAppointmentStatus());

    Log.d(TAG, "onBindViewHolder: appRespList---------"+appointmentlist);


    holder.mCradview.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AppCompatActivity activity = (AppCompatActivity) view.getContext();
            DetailAppointList detailAppointList = new DetailAppointList();

            activity.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content, detailAppointList).addToBackStack(null).commit();
        }
    });

}

@Override
public int getItemCount() {

        Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size());

      //**Here I'm getting Null Pointer exception**
        return appointmentlist == null ? 0 : appointmentlist.size();


    }

}

3 answers

  • answered 2017-10-11 10:17 gmetax

    change in your code the function getItemCount()

    @Override
    public int getItemCount() {
            //your problem is here because you are printing size of list which is null, 
            //so instead of that check the null first, then use the list object
            if (appointmentlist == null)
                Log.d(TAG, "null list");
            else 
                Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size());
    
          //**Here I'm getting Null Pointer exception**
            return appointmentlist == null ? 0 : appointmentlist.size();
    
    
        }
    
    }
    

  • answered 2017-10-11 10:27 Ghulam Moinul Quadir

    You are not handling the case in Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size()); line when appointmentlist is empty and you are calling appointmentlist.size(). That's why it is giving NullPointerException

  • answered 2017-10-11 11:50 Suhas

    I got answer after declaring ArrayList, appointmentlist as static in fetching JSON method (instance variable)

    public static ArrayList<AppointmentResponse.AppntRespData> appointmentlist;
    

    and Initialising it in OnResponse()

    i.e before for(int i=0;i<response.body().getData().size();i++)

    public void onResponse(@NonNull Call<AppointmentResponse> call, @NonNull Response<AppointmentResponse> response) {
    
                try {
                    if (response.isSuccessful()) {
    
                        appointmentlist = new ArrayList<AppointmentResponse.AppntRespData>();
    
                        for (int i=0;i<response.body().getData().size();i++) {
    
    
                            AppointmentResponse.AppntRespData mAppData = new AppointmentResponse.AppntRespData();