【发布时间】: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