Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 387
Rjz Satvara Avatar asked Nov 23 '18 14:11

Rjz Satvara


1 Answers

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
like image 155
theapache64 Avatar answered Oct 04 '22 19:10

theapache64