android - 房间数据库:即使它是自动生成的,仍然得到“没有为参数 'id' 传递值”
问题描述
这是我的房间实体:
@Entity(tableName = "matched_users")
data class MatchedUser(
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "match_id") val matchId: String
)
这是我在我的片段中实例化它:
private fun pass(){
CoroutineScope(coroutineContext).launch {
val match = MatchedUser()
CustomApplication.database?.matchedUsersDao()?.addMatchUid(match)
Log.d(TAG, "Added matchId to DB")
}
return removeUser2()
}
当我将鼠标悬停在它上面时,MatchedUser()
它仍然说我需要为id
.. 传递一个参数,但它应该按照实体中的说明自动生成。
知道为什么吗?
解决方案
在kotlin
数据类中,每个变量都应该被初始化,因此您可以在数据类构造函数中设置默认参数,如下所示:
@Entity(tableName = "matched_users")
data class MatchedUser(
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "match_id") val matchId: String
){
constructor(matchId: String): this(Int.MIN_VALUE, matchId)
}
现在您可以通过仅match_id
向constructor
数据类提供数据来插入数据,如下所示:
private fun pass(){
CoroutineScope(coroutineContext).launch {
val match = MatchedUser("1")
CustomApplication.database?.matchedUsersDao()?.addMatchUid(match)
Log.d(TAG, "Added matchId to DB")
}
return removeUser2()
}
推荐阅读
- asp.net - HttpClient.SendAsync exeption:底层连接已关闭:连接意外关闭
- java - 在 SQL 查询中转义换行符
- php - 在 Cloud SQL 中使用 LIKE 语句的 PDO 参数化查询
- r - 如何使用坐标原点从 R 中的 h5 文件投影光栅?
- cmake - Libwebrtc 和 cmake
- javascript - 使用角度 6 的画布调整窗口大小后单击侦听器不正确的数据
- javascript - 想要在具有相同类的多个元素上添加“addEventListener”
- r - 如何在 r 中的 rpart() 中关闭 k 折交叉验证
- android - 当设备的本地日期显式更改时,为什么 Firebase 会停止同步?
- javascript - 提交到mysql时Javascript计算字段消失