Cannot Create Instance Of Class ViewModel

后端 未结 3 1257
情歌与酒
情歌与酒 2020-12-22 00:43

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

相关标签:
3条回答
  • 2020-12-22 00:55

    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'
    
    0 讨论(0)
  • 2020-12-22 01:08

    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.

    0 讨论(0)
  • 2020-12-22 01:20

    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

    0 讨论(0)
提交回复
热议问题