Search code examples
androidsqliteandroid-sqliteandroid-roomandroidx

How to check whether record is delete or not in ROOM Database?


Using SQLite DB,

db.delete will return a long value that is the row ID of new row, or -1 if an error occurred. So you can check it to know delete is successful or not by :

int result = db.delete(TABLE_NAME, COLUMN_ID + " = ?",
                new String[]{String.valueOf(id)});
if(result != -1){
  // Deleted successful
}

But , in ROOM DB

we can delete record by :

 @Delete
 void delete(Notes notes);

Is there any option to check whether record deleted or not ?


Solution

  • You can simply define an Int return type to the @Delete method. The returned Int would be the numbers of rows deleted. (0 if nothing deleted)

    Example

    ProductsDao.kt

    @Dao
    interface ProductsDao {
    
        /**
         * To delete one or more products.
         * Returns number of rows deleted. 0 if no row deleted.
         */
        @Delete
        fun delete(vararg products: Product): Int // This is what you want
    
    }
    

    and I'd check if the row is deleted like this

    // one row
    val isDeleted = productsDao.delete(product) == 1
    
    // multiple rows
    val isDeleted = productsDao.delete(productList) == productList.size