3

Please notice that this issue is not systematic unlike other reported issues on StackOverflow.

I have a ViewModel that takes some parameters:

class MyViewModel(
        private val refreshTokenUseCase: RefreshTokenUseCase,
        ...
) : BaseViewModel() {

And a factory:

class MyViewModelFactory(
    private val refreshTokenUseCase: RefreshTokenUseCase,
    ...
) : ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return MyViewModel(refreshTokenUseCase, ...) as T
    }
}

and I create the ViewModel in the onCreate of the Activity:

    val myViewModel: MyViewModel by viewModels {
        MyViewModelFactory(refreshTokenInteractor)
    }
    model = myViewModel

in the onCreate of the Fragment I have:

val viewModel: MyViewModel by activityViewModels()
model = viewModel

Very randomly on Crashlytics I see crashes:

Caused by java.lang.InstantiationException: java.lang.Class<com.my.package.MyViewModel> has no zero argument constructor

I don't understand why the factory does not work and why a crash like this is not repeatable: it happened only once in 1 week and I have never managed to reproduce it running the app.

Do you see something wrong with the code?

One thing to add is that the crash always happens in the Fragment that gets the instance of the ViewModel that is supposed to have been created by the Activity. So the crash is on the line:

val viewModel: MyViewModel by activityViewModels()
1048576
  • 615
  • 9
  • 27
  • Does this answer your question? [Android ViewModel has no zero argument constructor](https://stackoverflow.com/questions/44194579/android-viewmodel-has-no-zero-argument-constructor) – Sam Chen Mar 24 '21 at 15:28
  • It doesn't unfortunatelly. That issue is systematic. The OP says: `However, when I run the code, I get exception:`. I wish that was happening to me. In my case it happens only very rarely with the live app. – 1048576 Mar 24 '21 at 15:39
  • You are using Hilt, you don't need a factory, just inject the ViewModel parameters. – m0skit0 Mar 25 '21 at 12:15
  • I'm not using Hilt and the question is mainly about how it is possible for this to happen. Either the ViewModel can be created or it can't. Why is the crash not systematic? – 1048576 Mar 26 '21 at 10:00
  • Anyway it is true that when I switched to Hilt I didn't have that problem anymore – 1048576 Mar 16 '22 at 10:02

0 Answers0