2017-10-11 5 views
-1

Dans mon projet, j'obtiens des données d'un serveur et les affiche dans un Recyclerview. Après avoir ajouté des données à une liste et l'avoir appelée dans getItemCount(), j'obtiens null et il y a une exception.getItemCount de l'adaptateur RecyclerView génère une exception NullPointerException

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

Mes données JSON méthode aller chercher

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

     } 
    }); 

Mon recycleur de classe Adaptateur

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


    } 

} 
+0

Vérifiez siz e de mAppData – YoLo

+0

try this 'return (null! = rendez-vous? dateList(): 0); ' –

+0

@ysl mAppData est la taille de l'objet et de la liste de rendez-vous est 2 – Suhas

Répondre

1

de changement dans votre code la fonction 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(); 


    } 

} 
+0

il montre null – Suhas

+0

@Suhas parce que votre liste est nulle, aussi sur votre code Je ne vois pas où vous utilisez le constructeur de l'adaptateur – gmetax

+0

droite! mais ai-je codé correctement dans la méthode OnResponse? obtenir des données et l'ajouter dans la liste et en appelant sa taille – Suhas

0

Vous ne gérez pas le cas dans Log.d(TAG, "getItemCount: list DATA-----" + appointmentlist.size()); ligne lorsque la liste de rendez-vous est vide et vous appelez appointmentlist.size(). Voilà pourquoi il donne NullPointerException

+0

oui je l'ai eu mais après l'avoir ajouté dans la liste de classe de haricot il devrait tenir la valeur juste? – Suhas

0

je suis arrivé réponse après avoir déclaré ArrayList, appointmentlist comme statique dans l'extraction méthode JSON (variable d'instance)

public static ArrayList<AppointmentResponse.AppntRespData> appointmentlist; 

et Initialiser dans 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();