Android Room Persistence库和Kotlin [英] Android Room Persistence library and Kotlin

查看:91
本文介绍了Android Room Persistence库和Kotlin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Kotlin和 Room Persistence Library . 我在Android持久性代码实验室中遵循了教程.

I am trying to write a simple app using Kotlin and Room Persistence Library. I followed the tutorial in the Android Persistence codelab.

这是我在Kotlin中的AppDatabase课:

Here is my AppDatabase class in Kotlin:

@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userModel(): UserDao

    companion object {
        private var INSTANCE: AppDatabase? = null
        @JvmStatic fun getInMemoryDatabase(context: Context): AppDatabase {
            if (INSTANCE == null) {
                INSTANCE = Room.inMemoryDatabaseBuilder(context.applicationContext, AppDatabase::class.java).allowMainThreadQueries().build()
            }
            return INSTANCE!!
        }

        @JvmStatic fun destroyInstance() {
            INSTANCE = null
        }
    }
}

但是当我尝试运行该应用程序时,它立即崩溃. 这是崩溃日志:

But when I tried to run the app, it crashes immediately. Here is the crash log:

Caused by: java.lang.RuntimeException: cannot find implementation for com.ttp.kotlin.kotlinsample.room.AppDatabase. AppDatabase_Impl does not exist
    at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:90)
    at android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:340)
    at com.ttp.kotlin.kotlinsample.room.AppDatabase$Companion.getInMemoryDatabase(AppDatabase.kt:19)
    at com.ttp.kotlin.kotlinsample.MainKotlinActivity.onCreate(MainKotlinActivity.kt:28)
    at android.app.Activity.performCreate(Activity.java:6272)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494) 
    at android.app.ActivityThread.access$900(ActivityThread.java:157) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)

似乎不是自动生成类AppDatabase_Impl.我检查了从codelab下载的原始Java应用程序,发现AppDatabase_Impl是自动生成的.

It looks like the class AppDatabase_Impl wasn't autogenerated. I checked the original java app downloaded from codelab and found that AppDatabase_Impl was autogenerated.

kotlin版本:1.1.2-3
会议室版本:1.0.0-alpha1

Kotlin version: 1.1.2-3
Room version: 1.0.0-alpha1

有没有人对此有经验?

使用kapt解决了我的问题.就我而言,我必须将annotationProcessor替换为kapt.

Using kapt solves my problem. In my case, I have to replace annotationProcessor with kapt.

推荐答案

通常在项目build.gradle中,我定义依赖项版本:

Usually in project build.gradle I define the dependencies versions:

ext {
    buildToolsVersion = '25.0.2'
    supportLibVersion = '25.3.1'
    espressoVersion = '2.2.2'
    archRoomVersion = '1.0.0-alpha1'
}

因此在应用程序build.gradle中,依赖关系如下:

so in app build.gradle the dependencies look like:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    compile "com.android.support:appcompat-v7:${rootProject.supportLibVersion}"

    compile "android.arch.persistence.room:runtime:${rootProject.archRoomVersion}"
    annotationProcessor "android.arch.persistence.room:compiler:${rootProject.archRoomVersion}"
    kapt "android.arch.persistence.room:compiler:${rootProject.archRoomVersion}"

    androidTestCompile("com.android.support.test.espresso:espresso-core:${rootProject.espressoVersion}", {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'
}

现在您可以在Kotlin中定义Entities Daos和Database.

Now you can define Entities Daos and Database in Kotlin.

数据库:

@Database(entities = arrayOf(User::class), version = 1)
abstract class Database : RoomDatabase() {
    abstract fun userDao(): UserDao
}

实体:

@Entity(tableName = "user")
class User {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
    var name: String = ""
}

道:

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>

    @Insert
    fun insertAll(vararg users: User)

    @Delete
    fun delete(user: User)
}

注意:使用参数查询. Kotlin重命名了params,因此通过userId检索属于用户的所有电子邮件的SQL查询是:

NB: Query with parameters. Kotlin renames params, so the SQL query to retrieve all the emails that belong at an user via the userId is:

@Query("SELECT * FROM email "
            + "INNER JOIN user ON user.id = email.userId "
            + "WHERE user.id = :arg0")
    fun getEmailsForUser(userId: Int): List<Email>

这篇关于Android Room Persistence库和Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆