1

Now that results.remove(0) is deprecated in realm, what is the best way to remove the realm element in an android application?

I have tried to delete particular element and I have used following code :

using result.deleteAllFromRealm(); it's delete all element but need to delete particular position.

RealmResults<PersonDetailsModel> results = myRealm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
        myRealm.beginTransaction();
        results.remove(0);     // App crash 
        myRealm.commitTransaction();

But it's app crash on that line and I am getting this error :

java.lang.UnsupportedOperationException: This method is not supported by 'RealmResults' or 'OrderedRealmCollectionSnapshot'.

Suggest some way to solved this issue.

Dinesh
  • 1,410
  • 2
  • 16
  • 29
  • Already answered here: https://stackoverflow.com/questions/36736178/how-to-delete-object-from-realm-database-android – jorjSB Dec 05 '17 at 11:52

4 Answers4

2
realm.executeTransaction((r) -> {
    r.where(PersonDetailsModel.class).equalTo("id", personId).findAll().deleteAllFromRealm();
});

Or

realm.executeTransaction((r) -> {
    PersonDetailsModel person = r.where(PersonDetailsModel.class).equalTo("id", personId).findFirst();
    if(person != null) {
        person.deleteFromRealm();
    }
});
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • I only added this answer because the `deleteFromRealm(index)` call is unreliable, and nobody posted `object.deleteFromRealm`. So if someone opens this page and doesn't go to the duplicate, they'll see mostly wrong answers. I have no guilty conscience over closing this as duplicate, nor providing an answer over the others that contains the "canonical way". – EpicPandaForce Sep 06 '18 at 10:52
1

Use deleteFromRealm method

result.deleteFromRealm(index);
sasikumar
  • 12,540
  • 3
  • 28
  • 48
0

Try this:

 realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmResults<PersonDetailsModel> result = realm.where(PersonDetailsModel.class).equalTo("id", personId).findAll();
            result.deleteAllFromRealm();
        }
    });

if didn't solve your issue then you can try below line:

result.deleteFromRealm(pos);
Muhammad Saad
  • 713
  • 1
  • 9
  • 31
0

You can use this code:

result.deleteFromRealm(index);
dralexnumber
  • 238
  • 2
  • 10