Persisting questionBank using SavedStateHandle

I am having issues with persisting questionBank after screen rotation with SavedStateHandle.

From Question.kt:


import androidx.annotation.StringRes

data class Question(@StringRes val textResId: Int, val answer: Boolean, var answered: Boolean = false)

Specifically, using the SavedStateHandle I don’t see how to persist the answered field in my class. The answered field was created as part of the challenge from Chapter 3 (Challenge: Preventing Repeat Answers)

Using the SavedStateHandle framework, would this be the correct implementation to get the field?

    var currentQuestionAnswered: Boolean
        get() = questionBank[currentIndex].answered

My problem is with setting questionBank[currentIndex].answered after a question has been answered and persisting the updated questionBank[currentIndex].answered value using SavedStateHandle. Using set(value: Boolean) = savedStateHandle.set(CURRENT_INDEX_KEY, true) is not correct as questionBank is not referenced.

Would onSavedInstanceState be the right approach here? Trying to avoid that as that would cause confusion in the implementation.

Would appreciate the help!

I think with your implementation, you would need to store all of the questionBank property in the SavedStateHandle. The problem is that, at this point in the book, you are limited to only storing simple data types (String, Int, etc.) in SavedStateHandle. You would need to do a little extra work in order to be able to save that state, but we do talk about it a bit later in the book (specifically Chapter 27).

Here is also some documentation that might help you out a bit: Parcelable implementation generator  |  Android Developers

1 Like