My app is crashing on some user's devices with the exception below.
Fatal Exception: java.lang.IllegalArgumentException: SavedStateProvider with the given key is already registered
at androidx.savedstate.SavedStateRegistry.registerSavedStateProvider(SavedStateRegistry.java:2)
at androidx.lifecycle.SavedStateHandleController.attachToLifecycle(SavedStateHandleController.java:2)
at androidx.lifecycle.SavedStateHandleController.create(SavedStateHandleController.java:1)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:1)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:5)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.java:5)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.java:5)
at com.emptysheet.pdfreader_autoscroll.homeScreen.MainActivity.getViewModel(MainActivity.java:3)
at com.emptysheet.pdfreader_autoscroll.homeScreen.MainActivity$scanDeviceForFiles$1$1.invokeSuspend(MainActivity.java:3)
at kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull(Intrinsics.java)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.java:4)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.java:7)
Everything is working fine on my devices. I don't get this exception on my own testing devices as well as on emulators. Also, I am using Hilt in my app.
Here is my ViewModel class.
class MainActivityViewModel @ViewModelInject constructor(
private val pdfItemRepository: PdfItemRepository
) : ViewModel() {
}
Here is the activity where I use this ViewModel.
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel:MainActivityViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
I am not using this MainActivityViewModel anywhere else except MainActivity. So there is no sharing of ViewModel. Also, the rotation is off on MainActivity. So there is no rotation change.
I came to understand from the error below that somehow my activity is trying to create another ViewModel instead of retaining the previous one?. Please correct me if I am wrong. I am unable to understand what kind of scenarios is triggering SavedStateRegistry.registerSavedStateProvider() again.
Note - I have omitted methods in my ViewModel class and activity to increase readability.