Search code examples
androidsqliteandroid-sqliteandroid-roomdao

Android Room Database - Query validation for success or failure


We are using Room database in android to store the data.

Now, In Dao class we all perform various queries like Insert, Select, Delete, Update etc.

I want to know that How can We know that these queries executed successfully?

i.e If I am doing as below :

appDatabase.userDao().insert(userData)

How Can I notified that the user data is inserted in particular table and operation is successful ?

And Yes Is there any tools or plugin available through which we can see the data of Room database? (I have googled about it, but it was a bit confused regarding Device Monitor)

Please guide.


Solution

  • Everything is explained in the documentation here.

    We can return a value for insert, update and delete operations to determine if it was successful or not.

    @Insert
    fun insert(item: ItemEntity): Long // returns row that entity was inserted at or -1 on failure
    
    @Update
    fun update(item: ItemEntity): Int // returns the number of rows updated successfully
    
    @Delete
    fun delete(item: ItemEntity): Int // returns the number of rows deleted successfully
    

    And then when you do the operation:

    val result = cache.insert(item.toItemEntity())
    println("result is $result")
    

    Queries don't seem to have an obvious way to implement this functionality though.