Android Room,如何保存一个实体,其中一个变量是密封的类对象

标签 android kotlin android-sqlite android-room sealed-class

我想在我的 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
)
它就像一个魅力

关于Android Room,如何保存一个实体,其中一个变量是密封的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60928706/

相关文章:

android - Titanium Studio - 合金|标签的字体大小

android - 如何在 SQLite 数据库中存储和检索字节数组(图像数据)?

android - SQLite 查询未按特定顺序执行

android - Kotlin - 接口(interface)中的只读属性

android - 在 Android 中删除整个数据库 onUpgrade?

java - 安卓 : How can i make my application multilingual?

java - ImageButton 和首选项

android - 在 Android 上订阅 ANCS

Kotlin 将时间戳转换为日期时间

android-studio - 强制 Android Studio 使用 gradle 4.1