在带有标题的RecyclerView中添加新项目,导致ArrayIndexOutOfBoundsException

时间:2018-09-08 14:16:29

标签: android android-recyclerview indexoutofboundsexception

我的RecyclerAdapter工作正常,但是当我向其中添加新项然后单击某些按钮时,将引发ArrayIndexOutOfBoundsException。

有两种情况填充我的列表,第一种是当有一个新插入的数据,从而使其位置位于顶部时,另一种是当用户向下滚动时,将加载另外4个先前的项目,以便分页。 / p>

这是用于添加新项目

 //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。职位有问题吗?我还检查了 getItem(holder.getAdapterPosition())的值,没关系。

1 个答案:

答案 0 :(得分:0)

因为这种方法:

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

您应该将其替换为:

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