RecyclerView throws IndexOutOfBoundsException When Attempting to Move Items

Hello everyone,

I’m having issues with moving items in my RecyclerView in Android. I’m using Realm as the database and have a custom adapter named FinanceListAdapter.

First, I fetch the data from the Realm database using the following method:

@JvmStatic
fun getFinanceItems(financeType: Int): RealmResults<FinanceItem> {
    return realm!!.query<FinanceItem>("financeType == $0", financeType).sort("sortId", Sort.ASCENDING).find()
}

Then I initialize my RecyclerView and its adapter:

DataHolder.financeOneItems = getFinanceItems(1)
recyclerView = binding!!.recyclerView
adapter = FinanceListAdapter(this, requireActivity(), requireContext(), this)
recyclerView!!.layoutManager = LinearLayoutManager(activity)
recyclerView!!.adapter = adapter
val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(this)
mItemTouchHelper = ItemTouchHelper(callback)
mItemTouchHelper!!.attachToRecyclerView(recyclerView)

Afterward, I try to move the items using the notifyItemMoved(fromPosition, toPosition) method. The code looks like this:

override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
    RealmManager.realm?.writeBlocking {
        val item1 = query<FinanceItem>("id == $0", DataHolder.financeOneItems?.get(fromPosition)!!.id).first().find()
        val item2 = query<FinanceItem>("id == $0", DataHolder.financeOneItems?.get(toPosition)!!.id).first().find()

        if ((item1 != null) && (item2 != null)) {
            val tempSortId = item1.sortId
            item1.sortId = item2.sortId
            item2.sortId = tempSortId

            activity?.runOnUiThread {
                adapter?.notifyItemMoved(fromPosition, toPosition)
            }
        } else {
            println("Error: Not enough items found.")
        }
    }
    return true
}

While doing this, I consistently get the following error:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionNormalViewHolder{b023ea1 position=7 id=-1}

The list I’m working with definitely has elements and the fromPosition and toPosition positions are valid within the list.

Does anyone have an idea what could be going wrong here? Any help would be greatly appreciated!