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) }