继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

集成room的坑解决

nickcau
关注TA
已关注
手记 113
粉丝 6508
获赞 303

Caused by: java.lang.RuntimeException: cannot find implementation for com.hy.room.HyDatabase. HyDatabase_Impl does not exist


必须要让gradle能集成

apply plugin: 'kotlin-kapt'


然后在项目gradle中引入:

implementation 'android.arch.persistence.room:runtime:1.1.1'
implementation 'android.arch.persistence.room:rxjava2:1.1.1'
kapt 'android.arch.persistence.room:compiler:1.1.1'

gradle的wrapper:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip


dependencies:

dependencies {
    classpath 'com.android.tools.build:gradle:3.1.3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}


不要用最新的3.4.1有坑

appdatabase的写法:

 */
@Database(entities = arrayOf(Cheese::class), version = 1)
abstract class CheeseDb : RoomDatabase() {
    abstract fun cheeseDao(): CheeseDao

    companion object {
        private var instance: CheeseDb? = null
        @Synchronized
        fun get(context: Context): CheeseDb {
            if (instance == null) {
                instance = Room.databaseBuilder(context.applicationContext,
                        CheeseDb::class.java, "CheeseDatabase")
                        .build()
            }
            return instance!!
        }

        /**
         * fill database with list of cheeses
         */
    }
}


dao的写法:

@Dao
interface CheeseDao {
    /**
     * Room knows how to return a LivePagedListProvider, from which we can get a LiveData and serve
     * it back to UI via ViewModel.
     */

    @Insert
    fun insert(cheeses: List<Cheese>)

    @Insert
    fun insert(cheese: Cheese)

    @Delete
    fun delete(cheese: Cheese)
}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP