Reputation: 4487
on iOS we can easily call realm.deleteAllObjects();
to remove all objects in our Realm database.
How do we achieve the same in Android?
Upvotes: 13
Views: 19265
Reputation: 914
Looks like the Realm API has changed. According to the docs, this is now the way
let all = realm.objects(Books.self)
realm.delete(all)
Don't forget to wrap it in a transaction if you haven't already.
try! realm.write {
let all = realm.objects(Rogets.self)
realm.delete(all)
}
Upvotes: -1
Reputation: 416
try {
val realm = Realm.getDefaultInstance()
realm.beginTransaction()
realm.delete<Dog>()
realm.insertOrUpdate(dogs)
realm.commitTransaction()
realm.close()
} catch (e: Exception) {
e.message
}
Upvotes: 0
Reputation: 6522
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
Upvotes: 22
Reputation: 5720
UPDATE 3.7.0
realm.beginTransaction();
realm.deleteAll();
//else realm.delete(obj_A.class);
realm.commitTransaction();
Upvotes: -1
Reputation: 854
For now clear()
is deprecated. Instead, referring to documentation you should use results.deleteAllFromRealm()
or realm.deleteAll()
or realm.delete(Dog.class)
.
Upvotes: 8
Reputation: 14470
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();
}
});
Upvotes: 23
Reputation: 141
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();
}
Upvotes: 3