androidandroid-recyclerviewactivity-lifecycle

How RecyclerView.Adapter StateRestorationPolicy works?


I populate my adapter asynchronously in onCreate method of my activity. When activity reconfigures, it destroys current activity and creates new activity instance. Hence my previous list will be lost. I have to again fill my adapter with new data. So by the time adapter restores its state, my list may not be populated yet. I think this is why adapter is always going to the starting position when an activity reconfig happens. I may be using this wrongly. Someone help me how to do this. This is my code:

override fun onCreate(savedInstanceState: Bundle?) {
    .
    .
    .
    myAdapter = MyListAdapter(myList,...)
    myAdapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
    .
    .
    .
    connectToDatabase(myList)
}
.
.
.
override fun onDistroy() {
    .
    .
    .
    disconnectFromDatabase()
}

Solution

  • I have the same problem with you. Though some people can make it work but for me it doesn't. A lot of people say it is not reliable. Instead I cache the adapter's data in ViewModel and everything works fine