kotlin 房间字段初始化为空

egdjgwm8  于 2023-02-24  发布在  Kotlin
关注(0)|答案(1)|浏览(135)

我正在编辑我的项目的现有实体,如下所示(我添加了sessionSettings字段):

data class Patient(
    
    // ... other fields
    
    @Expose
    @SerializedName("exo_settings")
    @Embedded
    var exoSettingsData: ExoSettingsData? = null,   // already exist

    @Expose
    @SerializedName("session_settings")
    @TypeConverters(SessionSettingsConverters::class)
    var sessionSettings: SessionSettings? = null,   // the new field
    
    /// ... other fields

)

我的类型转换器类:

class SessionSettingsConverters {
    private var gson = Gson()

    @TypeConverter
    fun stringToSessionSettings(data: String?): SessionSettings? {
        if (data.isNullOrEmpty()) {
            return null
        }

        val sessionSettingsType = object : TypeToken<SessionSettings>() {}.type

        return gson.fromJson(data, sessionSettingsType)
    }

    @TypeConverter
    fun sessionSettingsToString(someObject: SessionSettings): String? {
        return gson.toJson(someObject)
    }
}

我添加了会话设置;这是一个包含字符串和整数的基本对象,TypeConverter简化了集成。我的问题是,我需要这个字段默认为null,因为如果它是,我从另一个源获取数据。问题是,如果我这样做,我的单元测试会被破坏,如果我这样做,例如:

val patient1 = Patient("1", synkStatus = SynkStatus.DELETED)
centerDatabase.patientDao().savePatient(patient1).test()

它失败了(实体没有保存),但是如果我初始化一个SessionSettings对象,它就可以工作:

val patient1 = Patient("1", synkStatus = SynkStatus.DELETED, sessionSettings = SessionSettings())
centerDatabase.patientDao().savePatient(patient1).test()

所以我的问题是:是否有一种方法允许保存此实体而不初始化此字段以默认保持其为空?或者唯一的方法是添加一个布尔值以跟踪此字段是否已编辑?
谢谢

zbsbpyhn

zbsbpyhn1#

问题您的问题似乎是TypeConverter在转换SessionsSettings时不接受空值。
修正

变更为使用someObject: SessionSettings?,即添加了?

工作示例/演示

下面使用基于您的代码的代码演示了细微的变化,即:-

data class SessionSettings(
    val ssname: String,
    val ssine: Int
)

@Entity
data class Patient(
    @PrimaryKey
    val patientId: Long?=null,
    val patientName: String?=null,
    var sessionSettings: SessionSettings?,   // the new field
    /// ... other fields
)

class SessionSettingsConverters {
    private var gson = Gson()

    @TypeConverter
    fun stringToSessionSettings(data: String?): SessionSettings? {
        if (data.isNullOrEmpty()) {
            return null
        }
        val sessionSettingsType = object : TypeToken<SessionSettings>() {}.type
        return gson.fromJson(data, sessionSettingsType)
    }
    @TypeConverter
    fun sessionSettingsToString(someObject: SessionSettings?): String? {
        return gson.toJson(someObject)
    }
}

@Dao
interface SO75530351DAO {
    @Insert
    fun insert(patient: Patient): Long
    @Query("SELECT * FROM patient")
    fun getAllPatients(): List<Patient>
}

@TypeConverters(SessionSettingsConverters::class)
@Database(entities = [Patient::class], exportSchema = false, version = 1)
abstract class SO75530351DB: RoomDatabase() {
    abstract fun getDao(): SO75530351DAO
    companion object {
        private var instance: SO75530351DB?=null
        fun getInstance(context: Context): SO75530351DB {
            if (instance==null) {
                instance=Room.databaseBuilder(context,SO75530351DB::class.java,"so75539351.db")
                    .allowMainThreadQueries()
                    .build()
            }
            return instance as SO75530351DB
        }
    }
}

并使用上述:-

dbx = SO75530351DB.getInstance(this)
    daox = dbx.getDao()

    daox.insert(Patient(patientName = "Fred"))
    daox.insert(Patient(patientName = "Mary", sessionSettings = SessionSettings("SESSION1",10)))
    for(p in daox.getAllPatients()) {
        Log.d("DBINFO","Patient is ${p.patientName} ID is ${p.patientId} ${p.sessionSettings}")
    }

运行后的日志:-

D/DBINFO: Patient is Fred ID is 1 null
D/DBINFO: Patient is Mary ID is 2 SessionSettings(ssname=SESSION1, ssine=10)

通过应用程序检查,数据库:-

相关问题