4 Persisting UI State

Android does a great job of providing alternative resources at the right time. However, destroying and re-creating activities on rotation can cause headaches, such as GeoQuiz’s bug of reverting back to the first question when the device is rotated.

To fix this bug, the post-rotation MainActivity instance needs to know the old value of currentIndex. You need a way to save this data across a runtime configuration change, like rotation.

In this chapter you will fix GeoQuiz’s UI state loss on rotation bug by storing its UI data in a ViewModel. You will also address a less easily discoverable, but equally problematic, bug – UI state loss on process death – using Android’s saved instance state mechanism.

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.