在 Android 中使用 Room 时如何检查数据库中是否有特定项目?

How do I check if there's a certain item in database when using Room in Android?

@Dao
interface ExampleDao {

    @Query("SELECT * FROM example_table WHERE id = :id")
    fun get(id: Int): LiveData<Example>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(something: Example)
}

当我尝试使用下面的行检查数据库中是否有特定行时

val exists = dao.get(id).value != null
if (exists) {
    ...
}

exists variable always return null 我知道数据库中已经有该行并且 UI 正确显示信息。 为什么它总是 return null 以及如何检查房间数据库中是否有该行?

我会通过进行另一个查询来做到这一点 returns 如果项目存在则为真,如果不存在则为假。

@Query("SELECT EXISTS (SELECT 1 FROM example_table WHERE id = :id)")
fun exists(id: Int): Boolean

这样调用它,这样你就不需要检查它是否为 null:

val exists = dao.exists(id)