Deleting data from Room Database
Asked Answered
S

5

6

So I'm trying to completely clear my tables upon user log out but deleting the tables does not seem to stick and the old data is still there when another user logs in. I'm using RXJava Completables and Room and my code resembles the following.

                        mDbManager.deleteAllFromTable(mCompositeDisposable)
                            .doOnComplete(new Action() {
                                @Override
                                public void run() {
                                    //Finish logging out.
                                }
                            })
                            .subscribe();

Method in manager looks like

@Override
public Completable deleteAllFromTable(final CompositeDisposable compositeDisposable) {

    return Completable.fromAction(new Action() {
        @Override
        public void run() {
            mContactDao.deleteAllFromTable();
            vacuumTables(compositeDisposable);
        }
    }).subscribeOn(mSchedulerProvider.io())
            .observeOn(mSchedulerProvider.ui());
}

Method in Dao looks like

@Query("DELETE FROM table")
void deleteAllFromTable();

I've tried it without vacuuming the db and marking the Query as a Transaction and also creating an abstract method for the delete that also vacuums the table and marking that as a Transaction but the data still persists and the deleting is not finished when doOnComplete is called. Another thing I want to point out is that when deleting from the table there are other tables with data linked by foreign keys that are deleted as well.

Shiller answered 26/7, 2018 at 17:24 Comment(4)
How you know that data is not deleted?Infusorian
Using Device File Explorer in Android Studio... Also the next user who logs in can see the now logged out user's data.Shiller
is your database table actually called "table"?Nava
No... I put that just to be generic.Shiller
S
10

Instead of manually deleting all records from your tables, you can also use RoomDatabase.clearAllTables() method that will delete all rows from all the tables that are registered to this database as entities().

For more details, see this https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.html#clearAllTables()

Stud answered 10/9, 2018 at 11:43 Comment(0)
S
8

In DataBase

fun clearTables() {
        GlobalScope.launch(Dispatchers.IO) {
            [email protected]()
        }
    }

call the function in ViewModel

  YourDataBase.getInstance(mContext).clearTables()
Serialize answered 10/8, 2020 at 14:33 Comment(0)
A
2

Invoke method clearAllTables() from the class that extends Roomdatabase which Deletes all rows from all the tables that are registered to this database as entities().

Check the documentation here https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase

Accumulator answered 10/9, 2018 at 11:23 Comment(0)
H
1

Use clearAllTables() with RXJava like below inorder to avoid java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Completable.fromAction(new Action() {
    @Override
    public void run() throws Exception {
        getRoomDatabase().clearAllTables();
    }
}).subscribeOn(getSchedulerProvider().io())
        .observeOn(getSchedulerProvider().ui())
        .subscribe(new Action() {
            @Override
            public void run() throws Exception {
                Log.d(TAG, "--- clearAllTables(): run() ---");
                getInteractor().setUserAsLoggedOut();
                getMvpView().openLoginActivity();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.d(TAG, "--- clearAllTables(): accept(Throwable throwable) ----");
                Log.d(TAG, "throwable.getMessage(): "+throwable.getMessage());


            }
        });
Hillis answered 2/10, 2018 at 17:16 Comment(0)
T
1

I spent some time trying to connect Completable and Room database, and this is what worked for me. I would appreciate suggestions on how to clean it up:

public void eraseDB(){
    Log.d("Story act","delall");
    AppDB db = AppDB.getAppDatabase(context);
    Completable one = Completable.fromAction(() ->  db.clearAllTables());
    Completable.concatArray(one).observeOn(Schedulers.single()) // OFF UI THREAD
            .doOnSubscribe(__ -> {
                Log.w(TAG, "Begin transaction. " + Thread.currentThread().toString());
            })
            .doOnComplete(() -> {
                Log.w(TAG, "Set transaction successful."  + Thread.currentThread().toString());
            })
            .doFinally(() -> {
                Log.w(TAG, "End transaction."  + Thread.currentThread().toString());
            })
            .subscribeOn(Schedulers.single())
            .observeOn(AndroidSchedulers.mainThread()) // ON UI THREAD
            .subscribeWith(new CompletableObserver() {
                @Override
                public void onSubscribe(Disposable d) {
                    Log.w(TAG, "onSubscribe."  + Thread.currentThread().toString());
                }

                @Override
                public void onComplete() {
                    Log.w(TAG, "onComplete."  + Thread.currentThread().toString());
                    onDBErased();
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError." + Thread.currentThread().toString());
                }
            });
}

public void onDBErased(){
    FirebaseAuth.getInstance().signOut();
    startActivity(new Intent(context, LoginActivity.class));
    finish();
}
Totaquine answered 12/12, 2019 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.