Android Programming: The Big Nerd Ranch Guide, 5th Edition
by Bryan Sills, Brian Gardner, Kristin Marsicano, Chris Stewart
4 Persisting UI State
Destroying and re-creating activities on rotation can cause headaches, such as GeoQuiz’s bug of reverting to the first question when the device is rotated. To fix this bug, the post-rotation MainActivity instance needs to retain the old value of currentIndex. You need a way to save this data across a runtime configuration change, like rotation.
Luckily, there is a class that survives rotation that you can use to store your state. In this chapter, you will fix GeoQuiz’s UI state loss on rotation bug by storing its UI data in a ViewModel.
A ViewModel is the perfect complement to an Activity because of its simple lifecycle and ability to persist data across configuration changes. It is usually scoped to a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access