Cannot create an instance of class ViewModel kotlin

前端 未结 7 1838
礼貌的吻别
礼貌的吻别 2021-01-18 05:39

Here is my code

class BookmarkViewModel(app: Application) : AndroidViewModel(app) {

    private val dao = BookmarkDb.get(app).bookmarkDao()

    companion o         


        
相关标签:
7条回答
  • 2021-01-18 06:30

    Change viewModel = ViewModelProviders.of(activity!!).get(BookmarkViewModel::class.java)

    to viewModel = ViewModelProviders.of(this).get(BookmarkViewModel::class.java)

    Furthermore don't instantiate the viewModel to null. Change it to a lateinit var this way you don't have to instantiate immediately (but you are telling Kotlin that you will instantiate it before accessing it). You can do this like so: private lateinit var viewModel: BookMarkViewModel

    EDIT The root of the problem was that the Room Dependencies where either not on the same version or annotationProcessor was used instead of kapt (kapt is required when using Kotlin)

    0 讨论(0)
  • 2021-01-18 06:39

    remove kapt "xxxx.xxx." if you still use that in you gradle.build since it'e been deprecated and add

    apply plugin: 'kotlin-kapt'
    

    at the end of your gradle.build for the app module. that fixed my problem in android studio 3.1

    0 讨论(0)
  • 2021-01-18 06:39

    These 3 things worked for me:

    1. Adding/keeping both annotationProcessor and Kapt in the dependencies

    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" kapt "android.arch.lifecycle:compiler:$lifecycle_version"

    annotationProcessor "android.arch.persistence.room:compiler:$room_version" kapt "android.arch.persistence.room:compiler:$room_version"

    1. Addingapply plugin: 'kotlin-kapt' at the top of build.gradle(app) and cleaning the project

    2. Re-installing the application

    0 讨论(0)
  • 2021-01-18 06:40

    In my case this implementation solved my problem

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"

    before I implemented this only implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

    0 讨论(0)
  • 2021-01-18 06:41

    As somebody said here:

    Android room persistent: AppDatabase_Impl does not exist

    the solution was:

    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    
    
    implementation "androidx.paging:paging-runtime:$paging_version"
    
    0 讨论(0)
  • 2021-01-18 06:46

    in, my case I was added private set in DatabaseClass :| I removed it.

      private var INSTANCE: NoteDatabase? = null
                private set
    

    to :

    private var INSTANCE: NoteDatabase? = null
    

    this problem take my 2 hours :|||

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