OmriSoudry
OmriSoudry

Reputation: 371

android drag&drop with itemTouchHelper causes IndexOutOfBoundsException

I'm using itemTouchHelper to drag&drop/swipe-to-delete items in my RecyclerView list as described here. The items are switched/deleted with no problem, but since the buttons on the list items are created when onBindViewHolder is called, the POSITION that the button "remember" is not updated, and that causes many errors (mostly the IndexOutOfBound exception). Please help, I can't get it to work.

For example, let's say I have 2 items in the list, A and B. Then, I switch between them to get B and A. Then, I click on a CheckBox on B (which immediately updates the server). When I look in the server, A has a checked checkbox, NOT B (even though I clicked on B) because the position isn't updated on the call:

mValues.get(position).put("checkbox",true)

Here's the code:

@Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                Collections.swap(mValues, i, i + 1);
                notifyItemMoved(i, i + 1);
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                Collections.swap(mValues, i, i - 1);
                notifyItemMoved(i, i-1);
            }
        }

        return true;
    }

and:

@Override
    public void onItemDismiss(int position) {
        if (mValues.size() > position) {
            mValues.remove(position).deleteEventually();
            notifyItemRemoved(position);
        }
    }

Upvotes: 2

Views: 719

Answers (1)

user2213590
user2213590

Reputation:

the POSITION that the button "remember" is not updated,

Unlike the strategy of views "remembering" positions used in, eg, ListView adapters, a different approach is required in RecyclerView.

See this SO answer for an example solution.

Upvotes: 1

Related Questions