Android Room @Delete with parameters

JavaAndroidSqlAndroid Room

Java Problem Overview


I know I can't use DELETE in a query (that is a shame by the way), I will get the following error:

<i>Error:error: Observable query return type (LiveData, Flowable etc) can only be used with SELECT queries that directly or indirectly (via @Relation, for example) access at least one table.</i>

But I can't use @Delete(WHERE... xxx) So how do I delete a specific row by a parameter?

Java Solutions


Solution 1 - Java

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. If it is an int, the > value is the number of rows affected by this query.

Solution 2 - Java

The beauty of room is, we play with the objects. As per requirement you can use for kotlin:

@Delete
fun delete(model: LanguageModel)

for Java:

@Delete
void delete(LanguageModel model)

it will delete the exact object which is stored in the db with the same values. LanguageModel is my model class and it works perfectly.

Solution 3 - Java

You can use below method to delete by ID

@Query("DELETE FROM yourDatabaseTable WHERE id = :id")
void deleteById(int id);

for delete all rows

@Query("DELETE FROM yourDatabaseTable")
void delete();

Solution 4 - Java

ROOM database provides easy way to INSERT, UPDATE and DELETE an object in the database. To perform thus operation just needed to annotate @Delete. The DELETE operation returns the Int when deletion of the single object is successful returns 1 else returns 0 if the DELETE operation is unsuccessful, Adding the return type is a good practice.

KotlinEG.kt

   @Dao
   interface EntityLocalDAO {
       @Delete
       fun deleteData(entityObject: EntityObject) : Int
   }

javaEG.java

   @Dao
   interface EntityLocalDAO {
       @Delete
       int deleteData(EntityObject entityObject);
   }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackView Question on Stackoverflow
Solution 1 - JavaMaraguesView Answer on Stackoverflow
Solution 2 - JavaAwaisView Answer on Stackoverflow
Solution 3 - JavaFakhriddin AbdullaevView Answer on Stackoverflow
Solution 4 - JavaRohit SView Answer on Stackoverflow