Tom Darious
Tom Darious

Reputation: 523

How do I restore the previous RecyclerView state when a fragment is recreated?

I have a Fragment in my Android app that has a RecyclerView and I want to restore the RecyclerView it previously had from the last time the user opened the app.

In my Fragment I have the following blocks of code for saving and restoring the RecyclerView.

private val LIST_STATE_KEY = "recycler_state"
private var recyclerViewState : Parcelable? = null
private lateinit var recyclerView: RecyclerView

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putParcelable(LIST_STATE_KEY, recyclerView.layoutManager?.onSaveInstanceState())
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = rootView.findViewById(R.id.recycler_view)

    if (savedInstanceState != null) {
        recyclerViewState = savedInstanceState?.getParcelable(LIST_STATE_KEY)
    }
}

override fun onResume() {
    super.onResume()
    if (recyclerViewState != null) {
        recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewState)
        recyclerView.adapter?.notifyDataSetChanged()
    }
}

The problem I have now is when I open the app for the first time, I populate the RecyclerView, close the app, open it again and when I go to that specific fragment, the RecyclerView is empty. What am I doing wrong here? Why is my app not saving the RecyclerView data it previously had before the app closed and restoring the data it saved onto the RecyclerView when the app opens again?

Upvotes: 2

Views: 1526

Answers (1)

Leonid
Leonid

Reputation: 1179

Farid correctly says in the comment: These methods are used in cases when the Activity is destroyed, for example, when there is a lack of memory or when the configuration is changed (screen rotation and others). If you just clicked the Back button and thereby explicitly closed the Activity yourself, then these methods will not be executed.

If you want to have data after closing the application, then you must save this data to persistent memory. The Preference Library is suitable for storing the simplest variables. If the data structure is complex, then it is better to use Database.

Upvotes: 2

Related Questions