How to remove item from recyclerView in android
Remove the item in Arraylist in Android
holder.mRemoveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Get the clicked item label
String itemLabel = mDataSet.get(position);
// Remove the item on remove/button click
mDataSet.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mDataSet.size());
// Show the removed item label`enter code here`
Toast.makeText(mContext,"Removed : " + itemLabel,Toast.LENGTH_SHORT).show();
}
just try ,
int actualPosition = holder.getAdapterPosition();
in your removeItem()
method and replace position with actualPosition
.
like ,
private void removeItem(int position) {
int actualPosition = holder.getAdapterPosition();
model.remove(actualPosition);
notifyItemRemoved(actualPosition);
notifyItemRangeChanged(actualPosition, model.size());
}
I think you should call remove(holder.getAdapterPosition())
instead of remove(position)
because, when the holder's countdown finishes, it might have changed its position.
Suppose the following situation:
1º holder -> 5 seconds countdown
2º holder -> 10 seconds countdown
Since the second holder finishes after the first one, after 10 seconds, remove(1)
will be called but, since the first holder has already been removed, the second holder's position will be 0. Hence, it should call remove(0)
instead of remove(1)
(which will cause an IndexOutOfBoundsException
).