本文介绍了无法创建类ViewModel kotlin的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

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

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

    companion object {
        private const val PAGE_SIZE = PagingConstants.PERPAGE

        /**
         * If placeholders are enabled, PagedList will report the full size but some items might
         * be null in onBind method (PagedListAdapter triggers a rebind when data is loaded).
         * <p>
         * If placeholders are disabled, onBind will never receive null but as more pages are
         * loaded, the scrollbars will jitter as new pages are loaded. You should probably disable
         * scrollbars if you disable placeholders.
         */
        private const val ENABLE_PLACEHOLDERS = true
    }

        val allBookmarks = LivePagedListBuilder(dao.allBookmarkByDatetime(), PagedList.Config.Builder()
                    .setPageSize(PAGE_SIZE)
                    .setEnablePlaceholders(ENABLE_PLACEHOLDERS)
                    .build()).build()

    fun insert(title: String, description: String, datetime: String) = ioThread {
        dao.insert(Bookmark(id = 0, title = title, description = description, datetime = datetime))
    }

    fun remove(bookmark: Bookmark) = ioThread {
        dao.delete(bookmark)
    }
}

这是来自google示例.在我想要之后:

This is from the google samples..After I want to:

class BookmarkListFragment : FirstFragment() {

private var viewModel: BookmarkViewModel? = null
..

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

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

这是问题所在:

我可以在片段中使用它吗?

Can I use this in a fragment?

推荐答案

有人在这里说:

Android机房持久性:AppDatabase_Impl不存在

解决方案是:

实现"androidx.lifecycle:lifecycle-extensions:$ lifecycle_version" kapt"androidx.lifecycle:lifecycle-compiler:$ lifecycle_version"

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"

这篇关于无法创建类ViewModel kotlin的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 08:29