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 !

2
  • Implement ViewModel Commented Mar 24, 2021 at 14:17
  • Can you elaborate? Commented Mar 24, 2021 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.