android - How to autogenerate a Room database id without providing an id
问题描述
I am trying to create a room database and I want each item inserted into it to have its own unique id without me having to provide it, The problem is when I try to insert new items into the database I get an error asking me to provide an id.
Here is my entity:
@Entity(tableName = "notes_table")
data class Note(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo(name = "description")
val description: String,
@ColumnInfo(name = "priority")
var priority: Int)
Is there a way to have the database create its own auto-generated auto-increasing id column without having me having to add it like this:
val item = Note(id, item, priority)
insert(item)
And instead do this:
val item = Note(item, priority)
insert(item)
解决方案
Create a constructor
that takes item
and priority
as arguments
@Entity(tableName = "notes_table")
data class Note (var item: String,
@ColumnInfo(name = "priority")
var priority: String) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0,
//.....
}
推荐阅读
- excel - 导致有关 ActiveWorkbook.Save 的运行时错误的代码未在我的 Workbook_Open() 事件中触发
- reactjs - 使用来自 refs 的信息来设置状态时的无限重新渲染循环
- embedded - 为什么链接描述文件会有多个节命令?
- json - 将回调保存为流星会话变量的一部分
- jenkins - 如何防止两个不同的 Jenkins 管道同时运行?
- python - 在python中将比较打印为数字而不是真或假
- javascript - Excel不显示俄语单词。它只适用于英文单词
- c++ - 使用 Visual Studio Native cpp Unite 测试包含文件 I/O 的问题单元测试函数
- selenium - selenium 中的搜索上下文是什么意思以及 webdriver 实现搜索上下文接口的原因
- qt - 如何在 QHeaderView 中禁用自动渐变效果?