0

I am using a tabbed Activity. In one of the tabs I have two buttons and a Recyclerview. In the RecyclerView I have two spinners and an edittext. The purpose of the first button is to add a new item in the RecyclerView and the second one is to save the chosen elements in the spinners and edittexts.

My problem is that when the screen is rotated, the Recyclerview is emptied. I tried using the OnSaveInstanceState() and the OnRestoreInstanceState of the LayoutManager of the Recyclerview to save the state but it still gets deleted.

I'd appreciate any help !

1 Answers1

1

By default, activities and fragments have an onSaveInstanceState() method that the system uses to provide a Bundle to which you can write primitive data and parcelable objects.

This is okay as long as your data is simple. In your case, it isn't.

The framework may decide to destroy or re-create a UI controller in response to certain user actions or device events that are completely out of your control.

For example screen rotation (orientation change).

ViewModel comes to the rescue.

ViewModel is a class that’s part of the Android Architecture Components and it is lifecycle aware.

For more check this documentation.

Eyosiyas
  • 1,422
  • 1
  • 9
  • 25
  • So if I understood this correctly, I should save the Bundle from the Recyclerview in the Viewmodel for example in the OnPause of my fragment and then load it back from the Viewmodel to the Recyclerview in the onResume? – Hédi Guellouz Mar 25 '21 at 12:04