指定为非空的参数在房间数据库中为空错误
Parameter specified as non-null is null error in Room Database
这是我的实体 class:
@Entity
data class User(
@PrimaryKey
@Json(name = "id") val userId: String,
@Json(name = "login") val userName: String,
@Json(name = "avatar_url") val userAvatar: String,
val profile: Profile? = null
) : Serializable
这是我的个人资料数据class
data class Profile(
val avatar_url: String,
val bio: String,
val blog: String,
val company: Any,
val created_at: String,
val email: Any,
val events_url: String,
val followers: Int,
val followers_url: String,
val following: Int,
val following_url: String,
val gists_url: String,
val gravatar_id: String,
val hireable: Boolean,
val html_url: String,
val id: Int,
val location: String,
val login: String,
val name: String,
val node_id: String,
val organizations_url: String,
val public_gists: Int,
val public_repos: Int,
val received_events_url: String,
val repos_url: String,
val site_admin: Boolean,
val starred_url: String,
val subscriptions_url: String,
val twitter_username: Any,
val type: String,
val updated_at: String,
val url: String
) : Serializable
但是每次我尝试将数据插入 table 时都会收到错误消息,如何在使用房间数据库时在 table 中插入空数据对象?
这里的问题是 Room 不知道如何将 Profile 类型的属性插入 table.
简单的解决方案是使用类型转换器。类似于以下内容:
class DatabaseConverters {
@TypeConverter
fun toProfile(profileJson: String): Profile? {
return <Create a Profile object out of a JSON string>
}
@TypeConverter
fun fromProfile(profile: Profile?): String {
return <JSON string representation of Profile object>
}
}
在您的情况下 - 当 Profile 为 null 时,您可以使用“”(空字符串)。
有关转换器的更多信息:Here
这是我的实体 class:
@Entity
data class User(
@PrimaryKey
@Json(name = "id") val userId: String,
@Json(name = "login") val userName: String,
@Json(name = "avatar_url") val userAvatar: String,
val profile: Profile? = null
) : Serializable
这是我的个人资料数据class
data class Profile(
val avatar_url: String,
val bio: String,
val blog: String,
val company: Any,
val created_at: String,
val email: Any,
val events_url: String,
val followers: Int,
val followers_url: String,
val following: Int,
val following_url: String,
val gists_url: String,
val gravatar_id: String,
val hireable: Boolean,
val html_url: String,
val id: Int,
val location: String,
val login: String,
val name: String,
val node_id: String,
val organizations_url: String,
val public_gists: Int,
val public_repos: Int,
val received_events_url: String,
val repos_url: String,
val site_admin: Boolean,
val starred_url: String,
val subscriptions_url: String,
val twitter_username: Any,
val type: String,
val updated_at: String,
val url: String
) : Serializable
但是每次我尝试将数据插入 table 时都会收到错误消息,如何在使用房间数据库时在 table 中插入空数据对象?
这里的问题是 Room 不知道如何将 Profile 类型的属性插入 table.
简单的解决方案是使用类型转换器。类似于以下内容:
class DatabaseConverters {
@TypeConverter
fun toProfile(profileJson: String): Profile? {
return <Create a Profile object out of a JSON string>
}
@TypeConverter
fun fromProfile(profile: Profile?): String {
return <JSON string representation of Profile object>
}
}
在您的情况下 - 当 Profile 为 null 时,您可以使用“”(空字符串)。
有关转换器的更多信息:Here