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

1

9
@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 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?

Maffick answered 8/3, 2020 at 8:36 Comment(0)
C
22

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)
Cristobalcristobalite answered 8/3, 2020 at 11:12 Comment(2)
How we can check on main thread ? because db related query we cannt hit on main thread. I have used coroutine for the same but very 1st time its not give me correct result 2nd time onwards working fine.Oared
@Oared You could use coroutine for that purpose. move your code inside viewModelScope.launch{..} or any other scopeAnlage

© 2022 - 2024 — McMap. All rights reserved.