我尝试使用“房间”构建闹钟应用。我的方法repository.getAlarmById(1)
返回 null 。但是repository.getAlarms()
输出
警报(id = 1,min = 12,hour = 12,enabled = true,isRepeating = true)
警报(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) }
}
}
和报警类
@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 )
为什么我总是空值?
答案 0 :(得分:2)
您的代码似乎没问题。我的建议是检查两件事。
首先。将LIMITED 1
添加到您的查询中并进行检查
第二。如果仍然无法运行,请确保您的LiveData
正常运行。请记住,实时数据仅在对象更改时起作用!可能是这个问题存在,您可以手动将观察者添加到viewmodel
中。要测试此问题,只需从返回类型中删除LiveData
,然后再次检查即可。