I\'m currently working on a countdown app, and whenever I open it, it fails with a message saying Cannot create instance of class com.nailuj29gaming.CountdownViewModel
You need to upgrade to Fragment 1.2.0 or higher, which is what adds a support for the ViewModelProvider
constructor as per the Lifecycle 2.2.0 release notes:
You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality when using Fragment 1.2.0.
When using an older version of Fragments (i.e., the Fragment 1.1.0 that AppCompat 1.1.0 pulls in), you'll only get the ViewModelProvider$NewInstanceFactory
you see in your exception trace, rather than a ViewModel.Factory that supports AndroidViewModel
.
Therefore you should add an explicit dependency on Fragment 1.2.1 (the current latest):
implementation 'androidx.fragment:fragment:1.2.1'
This post helped me, as I was facing a similar issue: https://stackoverflow.com/a/60670866/6030520
To address the error you were getting
(Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
), you can simply add:
android {
...
kotlinOptions { jvmTarget = "1.8" }
}
... to your app/build.gradle file.
You should consider this line from the stacktrace
Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
This means you should pass an argument in the constructor when you buildng your viewmodel
In the link you quoted there is a specific kotlin answer]1
EDIT: And also control that you have correctly insta intiated the factory as shown in this response or this other one