Check if user exists in room databse through id

Viewed 91

I want to keep the app scanning for qr codes if it doesnt match the userId..

So my question is, how can I check if a user already exists in my room db?

 @Query("select * from user_table where id= :id")
    fun getUserById(id: Int) : User

I previously tried this, because I could need the user object in return by the function. But it only return a Kotlin.Unit

 val currentuser = mUserViewModel.getUserById(sId)
1 Answers

You could use

@Query("SELECT count() FROM user_table WHERE id=:id")
fun ifUserExists(id: Int): Boolean
  • This uses the count aggregate function to get the number of rows according to the WHERE clause. As the value returned will be either 0 (doesn't exist) or probably 1 (shouldn't be greater) does exist then this can directly be interpreted as a Boolean.
Related