在Android中使用Room时,如何检查数据库中是否存在某些项目? [英] How do I check if there's a certain item in database when using Room in Android?

查看:265
本文介绍了在Android中使用Room时,如何检查数据库中是否存在某些项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@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)
}

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

When I try to check if there's a certain row in the database using line below

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

exists变量始终返回null .我知道数据库中已经存在该行,并且UI正确显示了信息.为什么它总是返回null以及如何检查房间数据库中是否存在该行?

exists variable always return null I know there's the row already in the database and UI shows the info correctly. Why it always return null and how do I check if there's the row or not in the room database?

推荐答案

我将通过执行另一个查询来做到这一点,如果该项目存在,则返回true,否则返回false.

I would do it by making another query that returns true if the item exists or false if it doesn't.

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

并这样称呼它,因此您无需检查它是否为空:

And call it like this so you don't need to check if it's null or not:

val exists = dao.exists(id)

这篇关于在Android中使用Room时,如何检查数据库中是否存在某些项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆