Home » Android » How to truncate all tables in realm android

How to truncate all tables in realm android

Posted by: admin June 15, 2020 Leave a comment

Questions:

Hi im trying to truncateall tables in android when a user logs out. im using realms default path only.

realm = Realm.getInstance(getApplicationContext());

public void clearDB() {
    Realm.deleteRealmFile(instance);
}
How to&Answers:

Update

Use realm.delete(Foo.class) instead as clear() is deprecated. From 0.91.0
all @Deprecated methods will be removed.


Christian from Realm here.
That approach will work as long as you have closed all open Realm instances.
Another approach is clearing the tables you want like this:

realm = Realm.getInstance(getApplicationContext());

public void clearDB() {
  realm.executeTransaction(new Realm.Transaction() {
     @Override
     public void execute(Realm realm) {
        realm.clear(Foo.class);
        realm.clear(Bar.class);
     }
  });
}

You can read more here: http://realm.io/docs/java/0.77.0/api/io/realm/Realm.html#clear(java.lang.Class)

Answer:

use realm.delete(Myclass.class);

realm = Realm.getDefaultInstance();

    realm.beginTransaction();
    realm.delete(SuggestedAppDto.class);
    realm.delete(WifiSpotsDto.class);
    realm.commitTransaction();
    realm.close();

this worked for me.

Answer:

If you want to clear all tables, you may consider to use realm.deleteAll() method:

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.deleteAll();
realm.commitTransaction();
realm.close();

Answer:

Delete all tables:

Realm.init(fragmentActivity);
    RealmConfiguration realmConfig = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
    Realm realm = Realm.getInstance(realmConfig);
    realm.beginTransaction();
    try {
        realm.deleteAll();
        realm.commitTransaction();
    } catch (Exception e) {
        e.printStackTrace();
        realm.cancelTransaction();
    } finally {
        realm.close();
    }

delete one or more table:

  public void clearSearchHistory() {

    Realm.init(fragmentActivity);
    RealmConfiguration realmConfig = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
    Realm realm = Realm.getInstance(realmConfig);

    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.delete(Foo.class);
        }
    });


}

Answer:

If you want to clear all the tables without worrying about forgetting to clear new tables that you might create in the future, just do this

// mRealm is your realm instance

mRealm.beginTransaction();
Set<Class<? extends RealmModel>> tables = mRealm.getConfiguration().getRealmObjectClasses();
for (Class<? extends RealmModel> table : tables) {
    mRealm.delete(table);
}
mRealm.commitTransaction();