Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android Room, how to delete multiple rows in the table by id list

Having a Android Room with three tables timestamp, index, details, and all three have

@PrimaryKey @ColumnInfo(name = "id") var id: Int = 0

having fun clearDataByID(idList: List<Int>) to clear data from all three tables by the id in the idList

Dao as:

@Dao
interface DataDAO {


@Transaction
fun clearDataByID(idList: List<Int>) {
    deleteDataInTimestamp(idList)
    deleteDataIndex(idList)
    deleteDataDetails(idList)
}

@Query("delete from timestamp where id in :idList")
fun deleteDataInTimestamp(idList: List<Int>)

@Query("delete from index where id in :idList")
fun deleteDataIndex(idList: List<Int>)

@Query("delete from details where id in :idList")
fun deleteDataDetails(idList: List<Int>)
}

but it gets compiler error (similar for all three)

error: no viable alternative at input 'delete from timestamp where id in :idList'
public abstract void deleteDataInTimestamp(@org.jetbrains.annotations.NotNull()

if delete by single id it worked.

How to delete by a list of ids?

@Query("delete from timestamp where id = :id")
fun deleteSingleTimestamp(id: Int)
like image 468
lannyf Avatar asked Apr 02 '19 15:04

lannyf


People also ask

How do I remove all rows from a table in a room?

As of Room 1.1. 0 you can use clearAllTables() which "deletes all rows from all the tables that are registered to this database as entities()." I've included this as an answer below, but am reproducing here for visibility.

How delete all data from table in room database in Android?

3.1 Add the Clear all data menu optionIn the Options menu, select Clear all data. All words should disappear. Restart the app. (Restart it from your device or the emulator; don't run it again from Android Studio) You should see the initial set of words.

How do you write a delete query in DAO class?

Actually, you can use @Query to perform a delete. @Query("DELETE FROM users WHERE user_id = :userId") abstract void deleteByUserId(long userId); Extracted from Query javadoc: UPDATE or DELETE queries can return void or int.

How do I drop a table in a room database?

execSQL("DROP TABLE my_table"); // Use the right table name // OR: We could update it, by using an ALTER query // OR: If needed, we can create the table again with the required settings // database. execSQL("CREATE TABLE IF NOT EXISTS my_table (id INTEGER, PRIMARY KEY(id), ...)") } };


1 Answers

Thanks Simon points to the similar question, it should be done like:

@Query("delete from timestamp where id in (:idList)")
fun deleteDataInTimestamp(idList: List<Int>) 
like image 127
lannyf Avatar answered Sep 19 '22 14:09

lannyf