簡體   English   中英

在帶有標題的RecyclerView中添加新項導致ArrayIndexOutOfBoundsException

[英]Adding new item in RecyclerView with Header causing ArrayIndexOutOfBoundsException

我的RecyclerAdapter工作正常,但是當我向其中添加新項然后單擊某些按鈕時,將引發ArrayIndexOutOfBoundsException。

填充列表有兩種情況,一種是在有新插入的數據時將其放在頂部,另一種是在用戶向下滾動時將分頁顯示另外4個先前的項目。

這是用於添加新項目

 //This will be called only if user added some new post
                                      postList.add(0, post);
                                      //Notify the adapter that new item is added
                                      postRecyclerAdapter.notifyItemInserted(0);
                                      //Notify the adapter to update all position
                                      postRecyclerAdapter.notifyItemRangeChanged(0, postList.size() + 1 );

在分頁時,我通常只是添加舊數據

 postList.add(annonPost);
                            //Update the Recycler adapter that new data is added
                            postRecyclerAdapter.notifyItemInserted(postList.size());

這就是我的onBindViewHolder的樣子。

  @Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int position) {

    if (viewHolder instanceof ItemViewHolder){

        ItemViewHolder holder = (ItemViewHolder) viewHolder;

//I have a Firebase listeners here that updates the setAttributes automatically when a button is clicked
holder.setAttribute(someValueFromListener, 
postList.get(getItem(holder.getAdapterPosition())).name);
}}}

現在,因為我有標題,這就是我獲取位置和項目數的方法

 private int getItem(int position){
    return position - 1;
}

@Override
public int getItemCount() {
    return this.postList.size() + 1;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {

    if (position == 0)
        return TYPE_HEADER;

    return TYPE_ITEM;
}

可以添加新項目,但是一旦我開始單擊某個按鈕來觸發Firebase偵聽器,我就會得到java.lang.ArrayIndexOutOfBoundsException: length=12; index=-2 java.lang.ArrayIndexOutOfBoundsException: length=12; index=-2 職位有問題嗎? 我還檢查了getItem(holder.getAdapterPosition())的值,沒關系。

這是因為這種方法:

private int getItem(int position){
    return position - 1;
}

您應該將其替換為:

private int getItem(int position){
        return this.postList.get(position);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM