androidengineers.Book a session
โ† All interview questions
Android BasicsIntermediate3 min

A checkout survives rotation but loses the cart after backgrounding. How would you fix it?

Answer

First reproduce the difference between activity recreation and process recreation. A cart surviving rotation only demonstrates that an in-memory owner may have retained it; it does not prove persistence.

Use three layers:

  • A ViewModel coordinates the active checkout screen.
  • Saved state holds small restoration inputs, such as a cart ID and selected step.
  • A database or backend stores the cart and other business data that must outlive the screen.

On restoration, reload the cart by ID and recalculate availability and prices. Do not restore an old total as if it were authoritative.

Example

This ViewModel fragment keeps a restoration key rather than serializing the entire cart:

class CheckoutViewModel(
    private val savedState: SavedStateHandle
) : ViewModel() {
    val cartId = savedState.getStateFlow<String?>("cartId", null)

    fun selectCart(id: String) {
        savedState["cartId"] = id
    }
}

The repository observes or reloads the persisted cart for this ID. Never put large images or a complete response graph into saved state.

How to verify

Add items, background the app, terminate its background process, and reopen its retained task. Separately test normal recreation and a fresh launch. Force-stop and task dismissal are different scenarios; saved state is not a durable storage guarantee.

Follow-up to practise

What if the cart was deleted remotely? Render an explicit expired-cart state with a recovery action instead of repeatedly retrying or showing stale purchase details.

Reference

Android Developers: Save UI states

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising