In an Android photo editor, why does committing a FragmentTransaction when a filter render finishes after the user pressed Home crash with IllegalStateException, and how do you fix it?
answer
- the state was already captured
- after onStop since API 28
- commit refuses rather than lose it
- apply results only while started
- isStateSaved before showing
basics
~20 sOnce the host has run onSaveInstanceState, the FragmentManager's state is captured, so commit() throws IllegalStateException rather than make a change that would vanish on restore. Hold the result as state and commit only while the UI is at least STARTED.
solid answer
~50 sWhen the user presses Home, the activity stops and, on API 28 and higher, `onSaveInstanceState` runs right after `onStop`. At that point the `FragmentManager` has written its fragments and back stack into the saved state. A `commit()` arriving later from the render callback could not be part of that snapshot, so the `FragmentManager` throws `IllegalStateException` with "Can not perform this action after onSaveInstanceState" instead of silently losing it. `DialogFragment.show()` commits too, so it fails the same way. The fix is to stop driving fragment changes from asynchronous callbacks: keep the finished result in state that outlives the view, for example in a `ViewModel`, and apply it from a lifecycle-aware observer that only fires while the fragment or activity is at least `STARTED`. Check `isStateSaved` where a commit cannot be moved. Use `commitAllowingStateLoss()` only when losing that change on restoration is harmless.
code
kotlin · 21 linesclass FilterFragment : Fragment(R.layout.fragment_filter) {
private val viewModel: EditorViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Delivered only while the view lifecycle is at least STARTED,
// and fragments get ON_STOP before their state is saved.
viewModel.renderedResultId.observe(viewLifecycleOwner) { resultId ->
if (resultId != null) {
viewModel.onResultShown()
childFragmentManager.commit {
setReorderingAllowed(true)
replace<ResultPanelFragment>(
R.id.result_container,
args = bundleOf("resultId" to resultId),
)
}
}
}
}
}go deeper
Know that fragment changes go through a FragmentTransaction that you commit, and that committing while the app is in the background can crash.
Explain why the FragmentManager refuses commits after onSaveInstanceState, when that happens on API 28 and higher, and how commit differs from commitNow.
Trace the crash to an asynchronous callback, fix it by applying results while started, and audit commitAllowingStateLoss calls for hidden state loss.
Make 'callbacks update state, the UI applies it while started' a codebase rule, so whole classes of background-timing crashes cannot be written.
## What the exception protects A `FragmentManager` saves its whole state, every added fragment, their saved state and the fragment back stack, when its host saves instance state. If the process later dies, that snapshot is all that comes back. A transaction committed **after** the snapshot would change what is on screen now but be missing from what is restored, so the user would come back to a different screen than the one they left. Rather than allow that silently, `commit()` checks whether state has already been saved and throws `IllegalStateException` with the message **"Can not perform this action after onSaveInstanceState"**. The crash is the framework refusing a change it could not keep. ## When the window opens The order of the save matters: 1. The user presses Home. The activity gets `onPause` and `onStop`. 2. On **API 28 and higher**, `onSaveInstanceState` runs **after** `onStop`; before API 28 it ran before `onStop`. Either way the fragments see `ON_STOP` before their state is saved: the fragment documentation guarantees it, because the save itself moves them down to `CREATED`. 3. From the save until the host is started again, commits on that `FragmentManager` are refused. So the documentation calls `ON_STOP` the last point where a transaction on a fragment's child `FragmentManager` is safe. In the photo editor, the render runs on a background thread, finishes a few seconds after the user left, and its callback calls `supportFragmentManager.commit { replace<ResultFragment>(...) }`. The activity is stopped and its state is saved, so the app crashes in the background. Other places that fail the same way: - `DialogFragment.show()`, which commits a transaction to add the dialog; - a network or database callback that navigates; - a navigation library that issues fragment transactions for you. Jetpack Navigation's fragment navigator now **ignores** navigation operations after the `FragmentManager` has saved state to avoid this exception, so there the symptom is a navigation that silently never happened. ## Fixes, best first 1. **Keep the result as state and apply it while started.** The render writes its output ID to state that outlives the view, in one clause a `ViewModel`, and the fragment observes it with its `viewLifecycleOwner`. A lifecycle-aware observer only delivers while its owner is at least `STARTED`, so the commit runs when the user returns, before the next save can happen. If the process dies first, the rendered output must already be on disk, and the restored screen reloads it by its ID. 2. **Check before committing** when the call site cannot move. `FragmentManager.isStateSaved` tells you whether a commit would throw; defer the work until the host starts again. 3. **`commitAllowingStateLoss()`** performs the transaction even after the save. It is correct only when losing it on restore is harmless, such as removing a transient progress indicator. Using it to silence the crash just converts a crash into lost state. | Approach | Crash? | What the user sees after a process kill | |---|---|---| | `commit()` after the save | yes | crash, nothing to restore | | `commitAllowingStateLoss()` | no | the screen before the change | | Result kept as state, applied while `STARTED` | no | the result, restored from state | ## commit, commitNow and executePendingTransactions Interviewers often attach this follow-up: - `commit()` is **asynchronous**: it schedules the transaction to run on the main thread as soon as it can. - `commitNow()` runs it synchronously on the UI thread, but it cannot be combined with `addToBackStack()`. - `FragmentManager.executePendingTransactions()` runs every pending committed transaction now, and does work with the back stack. - Every transaction should call `setReorderingAllowed(true)`, so intermediate fragments skip lifecycle changes and animations run correctly. None of these helps with the crash: `commit()` itself is the call that refuses, so changing when an already-committed transaction executes changes nothing. ## Diagnosing it - The stack trace shows `commit` or `show` called from a callback, a handler or a listener, not from a lifecycle method or a click. - Reproduce by starting the long task, pressing Home before it finishes, and waiting. - Look for `commitAllowingStateLoss()` in the codebase: each one is a place where somebody already met this crash and may have traded it for lost state.
- Why does the same code crash on some devices only when the user leaves during the render?The commit is legal while the host is started and illegal between its saved state and its next start. If the render finishes while the editor is on screen, nothing happens; if the user presses Home first, the commit lands in that window. On API 28 and higher the save follows `onStop`, so the window opens when the activity becomes invisible.
- When is commitAllowingStateLoss() the right call?When the transaction's loss on restoration does not matter, for example removing a transient loading fragment or a change the screen recomputes anyway on recreation. It performs the commit after the save, so after a process kill the user sees the pre-change screen. For anything the user must find again, such as a result screen or a confirmation dialog, defer the commit instead.
- commitAllowingStateLoss is the standard fix and has no downside.
- The crash means the activity had already been destroyed.
- onSaveInstanceState runs before onStop on every API level.
- commit() runs the transaction immediately on the calling thread.
- Wrapping commit() in try/catch is a safe fix.
- Calling executePendingTransactions() right after commit() prevents the crash.
Assumes Android 17 (API 37): since API 28, onSaveInstanceState runs after onStop rather than before it, which moves the point where fragment commits start to fail.