Skip to content

Commit

Permalink
Fix LegacySavedStateHandleController null pointer exception when th…
Browse files Browse the repository at this point in the history
…e store is cleared during recreation

* `viewModelStore.keys()` returns a copy of the current keys, but `ViewModelStore.clear()` can be called before the for-each loop finishes. That would result in a null pointer exception because the returned `viewModel` is null, but we force-cast it to a non-null value with the double-bang (!!) operator.
* There is no risk in skipping null view models, as a store that has been cleared should not be attached to a `SavedStateHandle`, and any state would be cleared.

Test: N/A
Bug: 367431234
Change-Id: I6f16881b2f8dead781aa52a58c2652c8e40a35d9
  • Loading branch information
marcellogalhardo committed Nov 7, 2024
1 parent 8b16e9d commit db0d2c3
Showing 1 changed file with 5 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ internal object LegacySavedStateHandleController {
internal class OnRecreation : SavedStateRegistry.AutoRecreated {
override fun onRecreated(owner: SavedStateRegistryOwner) {
check(owner is ViewModelStoreOwner) {
("Internal error: OnRecreation should be registered only on components " +
"that implement ViewModelStoreOwner")
"Internal error: OnRecreation should be registered only on components " +
"that implement ViewModelStoreOwner. Received owner: $owner"
}
val viewModelStore = (owner as ViewModelStoreOwner).viewModelStore
val viewModelStore = owner.viewModelStore
val savedStateRegistry = owner.savedStateRegistry
for (key in viewModelStore.keys()) {
val viewModel = viewModelStore[key]
attachHandleIfNeeded(viewModel!!, savedStateRegistry, owner.lifecycle)
val viewModel = viewModelStore[key] ?: continue
attachHandleIfNeeded(viewModel, savedStateRegistry, owner.lifecycle)
}
if (viewModelStore.keys().isNotEmpty()) {
savedStateRegistry.runOnNextRecreation(OnRecreation::class.java)
Expand Down

0 comments on commit db0d2c3

Please sign in to comment.