首页 > 解决方案 > 房间数据库:即使它是自动生成的,仍然得到“没有为参数 '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.. 传递一个参数,但它应该按照实体中的说明自动生成。

知道为什么吗?

标签: androidkotlinandroid-room

解决方案


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_idconstructor数据类提供数据来插入数据,如下所示:

private fun pass(){
    CoroutineScope(coroutineContext).launch {
            val match = MatchedUser("1")
       CustomApplication.database?.matchedUsersDao()?.addMatchUid(match)
            Log.d(TAG, "Added matchId to DB")
        }
    return removeUser2()
}

推荐阅读