Cannot create an instance of class ViewModel kotlin

前端 未结 7 1842
礼貌的吻别
礼貌的吻别 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)

提交回复
热议问题