Search code examples
androidandroid-recyclerviewlistadapter

RecyclerView Crashes when delete first item if 'setHasStableIds(true)' is in adapter


My RecyclerView crashes if I set

init{
   setHasStableIds(true)
}

in my ListAdapter. If I remove this code it works without any issue. Logcat below

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.starsolutions.starfilemanager, PID: 10919
    java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 0(offset:-1).state:2 androidx.recyclerview.widget.RecyclerView{4a24664 VFED..... ......ID 0,147-1080,1878 #7f080181 app:id/rvExplorer}, adapter:com.starsolutions.starfilemanager.ui.ExplorerAdapter@efe3a61, layout:androidx.recyclerview.widget.LinearLayoutManager@e9986, context:com.starsolutions.starfilemanager.MainActivity@a4f9b5f
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6183)

Solution

  • My Id was the position of item in List.

    override fun getItemId(position: Int): Long = position.toLong()
    

    Now I replaced 'position.toLong()' with other unique numbers and the issue solved.