android - Android Room,如何保存一个实体,其中一个变量是密封的类对象
问题描述
我想在我的 Room 数据库中保存一个对象,其中一个变量可以是 on 类型或另一个。我认为密封类是有意义的,所以我采用了这种方法:
sealed class BluetoothMessageType() {
data class Dbm(
val data: String
) : BluetoothMessageType()
data class Pwm(
val data: String
) : BluetoothMessageType()
}
甚至这个,但没有必要。我发现这个给了我更多的错误,因为它不知道如何处理打开的 val,所以如果我找到第一个版本的解决方案,无论如何我都会很高兴。
sealed class BluetoothMessageType(
open val data: String
) {
data class Dbm(
override val data: String
) : BluetoothMessageType()
data class Pwm(
override val data: String
) : BluetoothMessageType()
}
然后是实体类
@Entity(tableName = MESSAGES_TABLE_NAME)
data class DatabaseBluetoothMessage(
@PrimaryKey(autoGenerate = true)
val id: Long = 0L,
val time: Long = Instant().millis,
val data: BluetoothMessageType
)
我还创建了一个 TypeConverter 来将其转换为字符串,因此我认为这不是问题。
首先,这可能吗?我认为这应该以与抽象类类似的方式起作用,但我也没有设法找到一个可行的解决方案。如果不可能,当我想保存一些可能是一种或另一种类型的数据(如果不是密封类)时,我应该采取哪种方法?
解决方案
就我而言,我做了以下事情:
sealed class Status2() {
object Online : Status2()
object Offline : Status2()
override fun toString(): String {
return when (this) {
is Online ->"Online"
is Offline -> "Offline"
}
}
}
class StatusConverter{
@TypeConverter
fun toHealth(value: Boolean): Status2 {
return if (value){
Status2.Online
} else{
Status2.Offline
}
}
@TypeConverter
fun fromHealth(value: Status2):Boolean {
return when(value){
is Status2.Offline -> false
is Status2.Online -> true
}
}
}
@Dao
interface CourierDao2 {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertStatus(courier: CourierCurrentStatus)
@Query("SELECT * FROM CourierCurrentStatus")
fun getCourierStatus(): Flow<CourierCurrentStatus>
}
@Entity
data class CourierCurrentStatus(
@PrimaryKey
val id: Int = 0,
var status: Status2 = Status2.Offline
)
它就像一个魅力
推荐阅读
- docker - 容器构建错误 - 无法关闭容器 - 容器在关闭期间遇到错误
- python - Python:从 argmin 在 3D 数组中广播 2D 索引数组
- android - 如何删除 RecycleView 项目之间的空格?
- ajax - Yii2 Pjax 更新 div 与 flash 消息问题
- forum - 如何将文件附加到此论坛中的答案?
- bash - 如何在单个 awk 命令中组合多个正则表达式条件?
- javascript - 添加 javascript 导致 div 不显示在网站上
- python - Python - 从 Selenium 中 ::before 伪元素上的 CSS 属性“内容”获取文本?
- jsx - Emmet 与样式化的组件自动完成
- javascript - 无法在 javascript 中将图像转换为 Base64 格式