romannurik/Android-SwipeToDismiss — pull request #8 by Gerlac (2013-11-08 16:20:47+00:00)
Title: Fixed IndexOutOfBoundsException when swiping penultimate+last item of th...

...e list

Hi Roman,

First of all, thanks for your library.

I've discovered a bug in the library that is quite easy to reproduce: if you swipe the penultimate item of the list and just right after you start swiping the last element of the list (keep it pressed) before the performDismiss() method of the penultimate item gets called, the application throws an IndexOutOfBoundsException.

If I am not wrong, that happens because when you swipe the penultimate item, mAdapter.notifyDataSetChanged() gets called in the onDismiss() callback, the view gets refreshed, and MotionEvent.ACTION_UP gets called using the mDownPosition saved when MotionEvent.ACTION_DOWN. If performDismiss() gets called (depending on the X of the touch event), you might end up trying to remove an element with a stale position from the list. In case it is the last item of the list, that will lead to an IndexOutOfBoundsException.

I know the bug depends on the current implementation of the callback method onDismiss() (depends if you try to remove the item from the adapter). But I think that's one of the most common implementations.

I've just restored mDownPosition = ListView.INVALID_POSITION; just after calling mCallbacks.onDismiss(mListView, dismissPositions); in order to restore mDownPosition so I can avoid dismissing a view with a stale position when this happens.

This is just a quick fix to avoid the crash, I might be missing some other stuff. Please let me know if there's a better way to solve the issue.

Regards,
Gerlac