How do you handle app configuration changes in Android, such as screen orientation change?
Instruction: Discuss strategies to manage configuration changes like screen orientation to prevent loss of data and state.
Updated
Official answer
Treat configuration change as a normal lifecycle event. Android commonly recreates the Activity to apply new resources for rotation, language, theme or window changes. Restore the user's task instead of assuming one screen object stays alive.
Keep business data and important drafts in durable storage. A ViewModel scoped to the appropriate owner can retain screen state across configuration recreation; its instance is lost on process death. Save small reconstruction inputs, such as a selected record ID, query or scroll anchor, through supported saved-state mechanisms. Rebuild large results from the repository rather than putting them into a Bundle.
The recreated UI loads resources for the current configuration and observes its state with the current lifecycle owner. A Fragment's View can be destroyed while the Fragment remains, so clear old bindings and collect against the view lifecycle. Do not retain Activity/View references in a ViewModel.
Do not recommend Fragment.setRetainInstance as a new solution; it is deprecated. Declaring configChanges also does not make the problem disappear: it transfers responsibility for specified changes to the app and does not prevent process death or every other recreation. Use it only when the component deliberately handles those changes and refreshes the relevant resources/layout.
Test a partly edited form during rotation, a language/theme switch, resizing and process recreation separately. Saving small state helps system recreation but is not a guarantee that a critical draft survives uninstall, force-stop or every termination path; persist that draft at an appropriate editing boundary.
Saved UI state, Configuration changes, Fragment retention deprecation