RecyclerView IndexOutOfBoundsException
For animation does not disappear, use:
holder.deleteItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, itemList.size());
}
});
Haven't read your code because I'm not familiar with the classes that you use but I know a fix to this problem. The problem occurs when the row element deleted is not the last one because of the index discrepancy between dataList
index (your ArrayList to store data) and the parameter final int position
in the method onBindViewHolder
. Let me explain the issue in a graphical manner:
suppose we have a RecyclerView with three rows and we delete the 3rd row, at dataList
index 2, (note that the deleted one is not the last element) after the removal, dataList
index for the last element reduces 3 from 2 however, final int position
still retrieves its position as 3 and that causes the problem. So, after removal, you can't use final int position
as an index of element to be removed from dataList
.
To fix this, introduce int shift=0
and in a while loop, try
removing the third item at (position-shift) and if it fails (in my case, it will) increment the shift and try removing it again until no exception occurs.
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
...
holder.removeButton.setOnClickListener(new View.OnClickListener(){ //button used to remove rows
@Override
public void onClick(View view) {
if (position == dataList.size() - 1) { // if last element is deleted, no need to shift
dataList.remove(position);
notifyItemRemoved(position);
} else { // if the element deleted is not the last one
int shift=1; // not zero, shift=0 is the case where position == dataList.size() - 1, which is already checked above
while (true) {
try {
dataList.remove(position-shift);
notifyItemRemoved(position);
break;
} catch (IndexOutOfBoundsException e) { // if fails, increment the shift and try again
shift++;
}
}
}
}
});
...
}