In my repository class, I want to fetch data only if none exists in a Room table. How to check whether any row exists in a table?
For check data exists or not you can get int value. @Query("SELECT * FROM TableName WHERE userName = :userName") int isDataExist(String userName); call this query using below code.
When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.
If nothing is found based on your criteria, it will return null.
Data Access Objects are the main classes where you define your database interactions. They can include a variety of query methods. The class marked with @Dao should either be an interface or an abstract class.
You can use EXISTS
operator and return just Boolean
:
@Query("SELECT EXISTS(SELECT * FROM table)")
fun hasItem(): Boolean
Use EXISTS
operator, and return 1 means true
and 0 means false
.
If you want to check some specific row and some condition, do this trick:
@Query("SELECT EXISTS(SELECT * FROM tableName WHERE id = :id)")
fun isRowIsExist(id : Int) : Boolean
Or simple use this:
@Query("SELECT EXISTS(SELECT * FROM tableName)")
fun isExists(): Boolean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With