Cannot create an instance of class ViewModel kotlin

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"
    

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


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)

Tags:

Android

Kotlin