Describe how to manage state in an Android application when the orientation changes.

Instruction: Explain the challenges and strategies related to state management when an Android device's orientation changes from portrait to landscape or vice versa.

Context: This question assesses the candidate's knowledge of handling runtime configuration changes, like screen orientation changes, to prevent data loss and ensure a seamless user experience.

Updated

Official answer

Orientation changes commonly recreate an Activity, but rotation is only one configuration change; resizing, locale and theme changes also matter. Rebuild the UI for the new configuration while preserving the state that should remain.

Separate three lifetimes. Keep active screen/business state in a correctly scoped ViewModel across configuration recreation. Save small reconstruction inputs with saved-instance-state APIs or SavedStateHandle so the system can restore them after eligible process recreation. Persist important user data, such as a draft note, in durable storage instead of relying on either in-memory object retention or a callback always running.

For a book-search screen, retain the query and current results in the ViewModel during rotation. Save the query and selected book ID as small state; after process recreation, load the results again from the repository. Do not place a large response or bitmap in a Bundle. Views with stable IDs can have state restored by the framework; preserve the superclass state handling.

Use lifecycle-aware observation and detach old view references. Fragment.setRetainInstance is deprecated; it is not the recommended state container. Handling selected configuration changes yourself creates a responsibility to update resources/layouts and does not solve process death.

Test rotation during an in-flight request, repeated resizing, back navigation and system-initiated process recreation separately. Verify the draft, selected item and loading/error state, rather than treating session length as proof that restoration is correct.

Saved UI state, Configuration changes

Related Questions