Search code examples
javaandroidrealm

Positions of RealmObjects change on deletion


Let’s say i have three objects/elements in my realm database:-

  1. A
  2. B
  3. C

When i delete the first element (i.e A) using the methoddeleteFromRealm(), the positions of the remaining two objects change like this:-

  1. C
  2. B

instead of:-

  1. B
  2. C

I wanna know why does this happen. Following is my code:-

public void onSwipe(int adapterPosition) {
    .
    .
    realm.beginTransaction();
    activity.getReminders().get(adapterPosition).deleteFromRealm();  //activity.getReminders() returns the RealmResults object
    realm.commitTransaction();
}

Solution

  • You need to sort your results to keep the order you want. Example from the doc :

    result = result.sort("age"); // Sort ascending
    result = result.sort("age", Sort.DESCENDING);
    

    https://realm.io/docs/java/latest/#sorting