这是我的房间实体:
@Entity(tableName = "matched_users")
data class MatchedUser(
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "match_id") val matchId: String
)
这是我在我的 fragment 中实例化它:
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()
}
关于android - 房间数据库 : Still getting "no value passed for parameter ' id' "even though it is meant to be autogenerated,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57646020/