Android Room: No value passed for parameter 'id'

更新日期: 2021-02-07 阅读次数: 5854 字数: 274 分类: Kotlin

使用 kotlin 定义了一个简单的 Room Entity 类 Todo,代码如下:

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "todos")
data class Todo(
    @PrimaryKey(autoGenerate = true) var id: Int,
    var title: String,
    var content: String,
) {
    override fun toString() = title
}

但是在新建 Todo 实例的时候,报错:

val todo = Todo(title = title, content = content)

报错内容为:

No value passed for parameter 'id'

解决方法

将 id 从构造函数中去除。

@Entity(tableName = "todos")
data class Todo(
    var title: String,
    var content: String,
) {
    @PrimaryKey(autoGenerate = true) var id: Int = 0

    override fun toString() = title
}

由于修改了 Entity 的实现,所以再次在模拟器里运行时,需要先卸载原来的 app,重新编译安装。

如果不卸载,会遇到的报错信息

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.

即便你更新了 database version,但是如果不写 migration 逻辑,依旧会报错。

java.lang.IllegalStateException: A migration from 1 to 2 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.

所以,最简单的方案就是卸载。

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式