Cannot create an instance of class ViewModel

后端 未结 23 2431
[愿得一人]
[愿得一人] 2020-12-05 12:37

I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

相关标签:
23条回答
  • 2020-12-05 13:05

    If constructor of your viewmodel is public and accepts only application then make sure you can create your own model without ViewModelProvider. Error message might be much more clear:

    val model = YouViewModel(app)
    
    0 讨论(0)
  • 2020-12-05 13:08

    Make sure your ViewModel has constructor with only one parameter i.e. Application.

    example:

    public YourViewModel(Application application) {
        super(application);
        ...
    
    0 讨论(0)
  • 2020-12-05 13:11

    Make the class and constructor public it solved my problem .

    0 讨论(0)
  • 2020-12-05 13:12

    If you are using Kotlin make sure to replace any annotationProcessor in build.gradle with kapt.

    Like:

    annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

    Will become

    kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"

    and add

    apply plugin: 'kotlin-kapt' on top of the buidl.gradle file.

    Annotation Processing with Kotlin

    0 讨论(0)
  • 2020-12-05 13:13
    1. Mostly, Solution is making Class and Constructor Public as the other answers
    2. It may also be a runtime error, check the Logcat Error Logs if there are multiple causes listed.
    0 讨论(0)
  • 2020-12-05 13:13

    if your PostViewModel class is an inner class, make sure its public and static

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