DEV Community

Cover image for Android Activity and Fragment Lifecycle: Real-World Examples and Interview Questions
Padmakar Garg
Padmakar Garg

Posted on

Android Activity and Fragment Lifecycle: Real-World Examples and Interview Questions

Almost every Android interview has a lifecycle question, and almost every production crash report has a lifecycle bug somewhere in it. The callbacks themselves are easy to memorize. What trips people up is knowing which callback to use for which job, and what happens when the system kills your process while the user is away.

This guide covers the Activity and Fragment lifecycle the way it shows up in real apps: rotation, process death, back stack, view binding leaks and collecting flows safely. It ends with interview questions and answers.

The Activity lifecycle in one table

Callback Called when Use it for
onCreate() Activity is first created Inflate UI, set up ViewModel, restore saved state
onStart() Activity becomes visible Start things that should run while visible
onResume() Activity is in the foreground and interactive Camera, sensors, anything exclusive
onPause() Another activity is taking focus Release exclusive resources, keep it fast
onStop() Activity is no longer visible Stop updates, save drafts
onDestroy() Activity is finishing or being recreated Final cleanup (not guaranteed on process death)
onRestart() Coming back from stopped state Rarely needed

Two rules that save a lot of pain:

  1. Pair your callbacks. Whatever you start in onStart(), stop in onStop(). Whatever you acquire in onResume(), release in onPause().
  2. onDestroy() is not a safe place to save anything. If the system kills your process for memory, it does not call it.

What actually happens on rotation

By default, a configuration change (rotation, dark mode switch, language change, font size) destroys the Activity and creates a new one. The sequence looks like this:

onPause -> onStop -> onSaveInstanceState -> onDestroy
-> onCreate (new instance) -> onStart -> onRestoreInstanceState -> onResume
Enter fullscreen mode Exit fullscreen mode

Everything in the old Activity instance is gone: fields, views, listeners. This is where the classic bug comes from.

Real-world bug 1: the form that clears itself

A user fills in a long signup form, rotates the phone, and every field is empty.

// Bad: state lives in the Activity and dies with it
class SignupActivity : AppCompatActivity() {
    private var draftEmail = ""
    // rotate the phone and draftEmail is "" again
}
Enter fullscreen mode Exit fullscreen mode

Fix it with a ViewModel, which survives configuration changes:

class SignupViewModel : ViewModel() {
    private val _state = MutableStateFlow(SignupState())
    val state: StateFlow<SignupState> = _state.asStateFlow()

    fun onEmailChanged(value: String) {
        _state.update { it.copy(email = value) }
    }
}

data class SignupState(val email: String = "", val password: String = "")
Enter fullscreen mode Exit fullscreen mode
class SignupActivity : AppCompatActivity() {
    private val viewModel: SignupViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_signup)

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { render(it) }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

ViewModel survives rotation, but it does not survive process death. That leads to the next problem.

Process death: the one most developers miss

When the user leaves your app and the system needs memory, it can kill your whole process. When the user comes back, Android recreates the Activity and restores the back stack, but your ViewModel is brand new and your singletons are empty.

You will not see this while testing normally. To reproduce it:

  1. Open your app and navigate to a deep screen.
  2. Press Home.
  3. Run adb shell am kill your.package.name.
  4. Open the app again from recents.

Or turn on Don't keep activities in Developer options.

Real-world bug 2: the checkout screen that crashes on return

A checkout screen reads the cart from an in-memory singleton. The user switches to a banking app to copy an OTP, Android kills your process, and the user returns to a checkout screen with an empty cart and a NullPointerException.

The fix is to keep small, essential state in SavedStateHandle and keep real data in a persistent store:

class CheckoutViewModel(
    private val savedState: SavedStateHandle,
    private val cartRepository: CartRepository
) : ViewModel() {

    // survives both rotation and process death
    var selectedAddressId: String?
        get() = savedState["address_id"]
        set(value) { savedState["address_id"] = value }

    // reloaded from Room/disk, not from a singleton
    val cart = cartRepository.observeCart()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
}
Enter fullscreen mode Exit fullscreen mode

A simple rule: IDs and small UI choices go in SavedStateHandle; real data comes from a database or network.

Choosing the right callback for the job

Real-world example: camera and video

Camera is an exclusive resource. Open it in onResume() and release it in onPause(), so another app can use it the moment yours loses focus.

With CameraX you rarely do this by hand, because bindToLifecycle() ties the camera to the lifecycle owner for you:

cameraProviderFuture.addListener({
    val provider = cameraProviderFuture.get()
    val preview = Preview.Builder().build().also {
        it.setSurfaceProvider(previewView.surfaceProvider)
    }
    provider.unbindAll()
    provider.bindToLifecycle(
        viewLifecycleOwner,
        CameraSelector.DEFAULT_BACK_CAMERA,
        preview
    )
}, ContextCompat.getMainExecutor(requireContext()))
Enter fullscreen mode Exit fullscreen mode

For video playback with ExoPlayer, the common advice is to create the player in onStart() and release it in onStop() on API 24+, because split-screen and multi-window mean your Activity can be visible without being in the resumed state.

Real-world example: location updates

Do not leave location updates running after the screen is gone. It drains battery and Play Store vitals will flag you.

override fun onStart() {
    super.onStart()
    fusedClient.requestLocationUpdates(request, callback, Looper.getMainLooper())
}

override fun onStop() {
    fusedClient.removeLocationUpdates(callback)
    super.onStop()
}
Enter fullscreen mode Exit fullscreen mode

Fragment lifecycle: two lifecycles, not one

This is the single most important thing to understand about Fragments, and the most common interview trap.

A Fragment has its own lifecycle and a separate view lifecycle. The Fragment instance can stay alive (for example on the back stack) while its view is destroyed.

onAttach -> onCreate -> onCreateView -> onViewCreated -> onViewStateRestored
-> onStart -> onResume
-> onPause -> onStop -> onDestroyView -> onDestroy -> onDetach
Enter fullscreen mode Exit fullscreen mode

When you navigate forward and the old Fragment goes onto the back stack, it goes through onDestroyView() but not onDestroy(). Its view is gone, its instance and ViewModel are still there. When the user presses back, onCreateView() runs again on the same Fragment instance.

Real-world bug 3: the ViewBinding memory leak

// Bad: binding outlives the view
class ProfileFragment : Fragment(R.layout.fragment_profile) {
    private lateinit var binding: FragmentProfileBinding

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding = FragmentProfileBinding.bind(view)
    }
}
Enter fullscreen mode Exit fullscreen mode

When this Fragment sits on the back stack, binding still references the destroyed view hierarchy. That keeps the whole view tree, and the Activity context behind it, in memory. LeakCanary will flag it.

The standard fix is to null the binding in onDestroyView():

class ProfileFragment : Fragment(R.layout.fragment_profile) {
    private var _binding: FragmentProfileBinding? = null
    private val binding get() = _binding!!

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentProfileBinding.bind(view)
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}
Enter fullscreen mode Exit fullscreen mode

Real-world bug 4: duplicate observers and double events

// Bad: observing with the Fragment lifecycle
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    viewModel.items.observe(this) { adapter.submitList(it) }
}
Enter fullscreen mode Exit fullscreen mode

Every time the view is recreated (back from another screen), you add another observer tied to the Fragment lifecycle. Updates fire multiple times and views that no longer exist get touched. Use the view lifecycle owner:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    viewLifecycleOwner.lifecycleScope.launch {
        viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.items.collect { adapter.submitList(it) }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

For LiveData the same rule applies: viewModel.items.observe(viewLifecycleOwner) { ... }.

Collecting Flow safely

Collecting a Flow directly in lifecycleScope.launch { } keeps collecting while the app is in the background, wasting work and sometimes crashing when you touch UI that is not there. Use repeatOnLifecycle:

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        launch { viewModel.uiState.collect(::render) }
        launch { viewModel.events.collect(::handleEvent) }
    }
}
Enter fullscreen mode Exit fullscreen mode

The block starts when the lifecycle reaches STARTED and is cancelled when it drops below it. When the user returns, it starts again from scratch.

Fragment Manager, back stack and results

Passing data between Fragments

Do not call methods on another Fragment directly, and do not use a static field. Two clean options:

1. Fragment Result API for one-off results:

// Receiver (e.g. list screen)
parentFragmentManager.setFragmentResultListener("filter_key", viewLifecycleOwner) { _, bundle ->
    val category = bundle.getString("category")
    viewModel.applyFilter(category)
}

// Sender (e.g. filter bottom sheet)
parentFragmentManager.setFragmentResult(
    "filter_key",
    bundleOf("category" to "shoes")
)
Enter fullscreen mode Exit fullscreen mode

2. Shared ViewModel scoped to the Activity or a navigation graph, for state that two screens genuinely share:

private val sharedViewModel: CheckoutFlowViewModel by activityViewModels()
Enter fullscreen mode Exit fullscreen mode

commit vs commitAllowingStateLoss

If you commit a Fragment transaction after onSaveInstanceState(), you get IllegalStateException: Can not perform this action after onSaveInstanceState. This usually happens when a network callback arrives after the user has left the screen. The right fix is not to reach for commitAllowingStateLoss() blindly. Collect results with repeatOnLifecycle so navigation only happens while the screen is started.

A word on Jetpack Compose

Compose changes how you write UI, not how Android works underneath. Your Activity still goes through the same lifecycle, and process death still kills your state. In Compose:

  • Use rememberSaveable for UI state that must survive recreation.
  • Use collectAsStateWithLifecycle() to collect flows lifecycle-aware.
  • Use DisposableEffect or LifecycleEventEffect to react to lifecycle events.
@Composable
fun ProfileScreen(viewModel: ProfileViewModel = viewModel()) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    var query by rememberSaveable { mutableStateOf("") }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Interview questions and answers

1. What is the order of Activity lifecycle callbacks when you open a new Activity B from Activity A?

A onPause(), then B onCreate(), onStart(), onResume(), and only then A onStop(). This is why onPause() must be fast: B does not appear until A's onPause() returns.

2. What happens when the screen rotates?

The Activity is destroyed and recreated: onPause, onStop, onSaveInstanceState, onDestroy, then onCreate, onStart, onRestoreInstanceState, onResume. A ViewModel survives this; fields on the Activity do not.

3. What is the difference between onSaveInstanceState() and a ViewModel?

onSaveInstanceState() writes a small Bundle that survives both configuration change and process death, but is limited in size (keep it to a few KB). A ViewModel holds larger in-memory state and survives configuration change only. In practice you combine them using SavedStateHandle.

4. Is onDestroy() always called?

No. If the system kills the process, it is not called. Never rely on it to save data.

5. What is the difference between onPause() and onStop()?

onPause() means the Activity lost focus but may still be partly visible (a dialog, or split-screen). onStop() means it is no longer visible at all.

6. How do you handle configuration changes without recreating the Activity?

Declare android:configChanges in the manifest and handle onConfigurationChanged() yourself. It is usually discouraged because you then have to handle every change manually, and it does nothing for process death. Prefer ViewModel and saved state.

7. What is the difference between Fragment lifecycle and view lifecycle?

The Fragment can outlive its view. On the back stack, the view is destroyed (onDestroyView) while the Fragment instance remains. That is why you observe data with viewLifecycleOwner and null out view binding in onDestroyView().

8. Why use viewLifecycleOwner instead of this when observing LiveData in a Fragment?

Using this ties the observer to the Fragment lifecycle. After the view is recreated you add a second observer without removing the first, causing duplicate updates and access to destroyed views.

9. add() vs replace() in FragmentTransaction?

replace() removes the existing Fragment's view and adds the new one, so the old Fragment goes through onDestroyView(). add() leaves the previous Fragment's view in place underneath. With replace() plus addToBackStack(), the old Fragment is kept as an instance and recreates its view on back.

10. How do two Fragments communicate?

Use the Fragment Result API for one-off results, or a shared ViewModel scoped to the parent Activity or navigation graph for shared state. Avoid direct references between Fragments and avoid interfaces that force the Activity to be a relay.

11. What is process death and how do you test it?

The system kills the app process while it is in the background. Test with "Don't keep activities" or adb shell am kill <package>. Defend against it with SavedStateHandle, rememberSaveable and persistent storage.

12. Why does lifecycleScope.launch { flow.collect {} } waste resources?

It keeps collecting while the app is in the background. Use repeatOnLifecycle(Lifecycle.State.STARTED) or flowWithLifecycle so collection stops when the UI is not visible.

13. What is onNewIntent() and when does it matter?

When an Activity with launchMode="singleTop", singleTask or singleInstance is already running and receives a new intent, the system calls onNewIntent() instead of creating a new instance. Typical case: tapping a notification should open the existing screen with new data, not stack a second copy.

14. Where would you start and stop a video player?

On API 24 and above, start in onStart() and release in onStop(), since multi-window means the Activity can be visible without being resumed. Below API 24, use onResume() and onPause().

15. How do you debug a lifecycle bug?

Log each callback with Log.d or use Android Studio's Logcat filters, enable "Don't keep activities", test rotation and process death, and run LeakCanary to catch leaked views and Contexts.

Quick checklist before you ship a screen

  • Rotate the device mid-flow. Does state survive?
  • Enable "Don't keep activities". Does the screen restore correctly?
  • Go to another screen and back. Do observers fire only once?
  • Is every resource acquired in a callback released in its matching one?
  • Is view binding nulled in onDestroyView()?
  • Are Flows collected with repeatOnLifecycle or collectAsStateWithLifecycle?

Further reading

If you want to see these patterns in real code, my open-source Android projects are on GitHub.


About the author: Padmakar Garg is a Senior Android Developer with 8+ years of experience in Kotlin, Jetpack Compose, Kotlin Multiplatform and mobile security. Portfolio and blog: gargpadmakar.github.io. Connect on LinkedIn.

Top comments (0)