Delete method for Room Database is not working

Viewed 1285

I have a DAO method like this

@Query("DELETE FROM Weather WHERE name = :name")
Completable deleteDataByName(String name);

Weather object

@Entity
public class Weather {

    @PrimaryKey(autoGenerate = true)
    public int id;
    public String name;
    public String date;
    public String description;
    public String icon;
    etc.

Data is not deleted when I call deleteDataByName method. How can I fix it? There are 16 Weather objects in the database with the same name How can I delete them? enter image description here

enter image description here

enter image description here

3 Answers

I had the same issue and is resolved by using androidx components. Try with updated room components

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:$room_version"

    // optional - RxJava support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

Probably you need to use a room version higher or equal than 2.1.0 If you are using gradle to build your app go to the project gradle file and add those lines:

ext {
    roomVersion = '2.1.0-rc01'
}

Then you can update your room dependency in the app gradle with this:

implementation "androidx.room:room-rxjava2:2.1.0"
implementation "androidx.room:room-runtime:$rootProject.roomVersion"

Also you can find more information here.

EDIT This is a complete app gradle that you probably need (plus your others dependencies):

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
  ...
}

allprojects {
    repositories {
        ...
    }
}

dependencies {

    // Room components
    implementation "androidx.room:room-runtime:$rootProject.roomVersion"
    implementation "androidx.room:room-rxjava2:2.1.0"
    kapt "androidx.room:room-compiler:$rootProject.roomVersion"
}

I read your comment:

private void getDeleteByName(String city) { mAppDatabase.getWeatherDao().deleteDataByName(city); } – Vadim Fedchuk 2 days ago

You are not calling it right. Your mAppDatabase.getWeatherDao().deleteDataByName(city) will do nothing by itself, it's Completable. You have to subscribe to it to make it work.

Related