SELECT 查询 returns null 尽管对象存在 Kotlin\Room

SELECT query returns null though the object exist Kotlin\Room

我正在尝试使用 Rooms 构建闹钟应用程序。我的方法repository.getAlarmById(1)returnsnull。但是repository.getAlarms()输出

Alarm(id=1, min=12, hour=12, enabled=true, isRepeating=true)

Alarm(id=2, min=13, hour=13, enabled=true, isRepeating=true)

这里是AlarmDao

@Dao
interface AlarmDao {

    @Query("SELECT * FROM alarm_table")
    fun getAll(): LiveData<List<Alarm>>

    @Query("SELECT * FROM alarm_table WHERE id = :id")
    fun getById(id: Int): LiveData<Alarm>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(alarm: Alarm)

    @Delete
    fun delete(alarm: Alarm)
}

AlarmRepository

class AlarmRepository (private val alarmDao: AlarmDao): AlarmDataSource {

    override fun getAlarms(): LiveData<List<Alarm>> {
        return alarmDao.getAll()
    }

    override fun getAlarm(id: Int): LiveData<Alarm> {
        return alarmDao.getById(id)
    }

    override fun saveAlarm(alarm: Alarm) {
        doAsync { alarmDao.insert(alarm) }
    }

    override fun deleteAlarm(alarm: Alarm) {
        doAsync { alarmDao.delete(alarm) }
    }
}

报警class

@Entity(tableName = "alarm_table")
data class Alarm(
        @PrimaryKey
        var id: Int = 0,

        @ColumnInfo(name = "min")
        var min: Int = -1,

        @ColumnInfo(name = "hour")
        var hour: Int = -1,

        @ColumnInfo(name = "enabled")
        var enabled: Boolean = true,

        @ColumnInfo(name = "isRepeating")
        var isRepeating: Boolean = false )

为什么我总是得到空值?

你的代码看起来没问题。我的建议是检查两件事。

首先。将 LIMITED 1 添加到您的查询并检查它

其次。如果仍然无法正常工作,请确保您的 LiveData 正常工作。请记住,实时数据仅在对象更改时才起作用!此问题可能存在问题,您可以手动将观察者添加到 viewmodel。要测试此问题,只需从 return 类型中删除 LiveData 并再次检查即可。