Delete All Realm Objects During Runtime

For now clear() is deprecated. Instead, referring to documentation you should use results.deleteAllFromRealm() or realm.deleteAll() or realm.delete(Dog.class).


I'm use this for delete all objects:

    private void clearAllRealmPerson(){

        Realm realm = Realm.getDefaultInstance();

        realm.beginTransaction();
        realm.clear(Person.class);
        realm.commitTransaction();
        realm.close();
   }

Delete all objects from Realm database:

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

Delete all objects of a kind from Realm database:

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

Delete the results of a query:

final RealmResults<Dog> results = realm.where(Dog.class).findAll();

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // remove single match
        results.deleteFirstFromRealm();
        results.deleteLastFromRealm();

        // remove a single object
        Dog dog = results.get(5);
        dog.deleteFromRealm();

        // Delete all matches
        results.deleteAllFromRealm();
    }
});

You can do this by using results- For instance, if I want to delete all Dog objects, I can do the following-

// obtain the results of a query

RealmResults<Dog> results = realm.where(Dog.class).findAll();

// All changes to data must happen in a transaction
realm.beginTransaction();

// Delete all matches
results.deleteAll();

realm.commitTransaction();

Ref: documentation

Tags:

Java

Realm