【问题标题】:Adding new item in RecyclerView with Header causing ArrayIndexOutOfBoundsException在 RecyclerView 中添加带有 Header 的新项目导致 ArrayIndexOutOfBoundsException
【发布时间】:2019-02-13 14:39:38
【问题描述】:

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

【问题讨论】:

    标签: android android-recyclerview indexoutofboundsexception


    【解决方案1】:

    那是因为这个方法:

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

    您应该将其替换为:

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

    【讨论】:

    • 你能解释一下两者之间的最大区别是什么吗?
    • 目前你没有返回你正在播种的列表的值,你只是返回一个指向项目前一个位置的索引。
    • 在你的回答中你返回的是一个列表而不是索引?
    • 如果您编辑您的问题并将您的适配器类和 viewHolder 类放在这里,我可以为您提供更好的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 2018-11-03
    • 1970-01-01
    • 2018-04-07
    相关资源
    最近更新 更多