简体   繁体   English

RecyclerView 适配器的 getItemCount 抛出 NullPointerException

[英]RecyclerView adapter's getItemCount throws NullPointerException

In my project, I am fetching data from a server and displaying it in a Recyclerview.在我的项目中,我从服务器获取数据并将其显示在 Recyclerview 中。 After adding data to a list and calling it in getItemCount(), I get null and it throws an exception.将数据添加到列表并在 getItemCount() 中调用它后,我得到null并引发异常。

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我的JSON数据获取方法

 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();


    }

}

change in your code the function getItemCount()在您的代码中更改函数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();


    }

}

You are not handling the case in Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size());您没有在Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size());处理该案例Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size()); line when appointmentlist is empty and you are calling appointmentlist.size() .当约会列表为空并且您正在调用appointmentlist.size() That's why it is giving NullPointerException这就是它给出NullPointerException的原因

I got answer after declaring ArrayList, appointmentlist as static in fetching JSON method (instance variable)在获取 JSON 方法(实例变量)中将ArrayList、appointmentlist声明为静态后我得到了答案

public static ArrayList<AppointmentResponse.AppntRespData> appointmentlist;

and Initialising it in OnResponse()并在 OnResponse() 中初始化它

ie 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RecyclerView Adapter 返回 NullPointerException - RecyclerView Adapter return NullPointerException 我的 RecyclerView 适配器的 getItemCount() 返回 0,即使里面有项目 - getItemCount() of my RecyclerView adapter returns 0 even though I have items in it RecyclerView 不调用 getItemCount - RecyclerView not calling getItemCount 视图在RecyclerView Adapter中的onBindViewHolder中返回NullPointerException - Views return NullPointerException in onBindViewHolder in RecyclerView Adapter 适配器崩溃,方法 getItemCount nullpointer - Crash in adapter, in method getItemCount nullpointer Recyclerview适配器的notifyDataSetChanged不更新RecyclerView - Recyclerview Adapter's notifyDataSetChanged not updating RecyclerView RecyclerView 里面的 RecyclerView 弄错了 getItemCount() - RecyclerView inside RecyclerView made wrong getItemCount() RecyclerView getChildCount() 和 getItemCount() 返回相同的值 - RecyclerView getChildCount() and getItemCount() returns same value RecyclerView:没有附加适配器; 跳过布局和 java.lang.NullPointerException - RecyclerView: No adapter attached; skipping layout and java.lang.NullPointerException RecyclerView未被填充(getItemCount()返回零) - RecyclerView not being populated (getItemCount() is returning zero)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM