Weizhi Weizhi - 1 month ago 11
Android Question

RealmList in RealmObject. How to persist order?

I have a

RealmObject
with a
RealmList
as one of its field.

public class ToyMaker extends RealmObject {
private RealmList<Toy> toyList;
...
}

public class Toy extends RealmObject {
...
}



  1. Will the ordering of
    Toy
    in
    toyList
    be persisted when written to Realm and reading it back?

  2. If ordering is not persisted by Realm, how can i achieve this manually given that

    A. I cannot add additional fields (e.g. index) in
    Toy
    class (a
    Toy
    can have many
    ToyMaker
    so an index field in
    Toy
    is not feasible.

    B. The ordering is in the order that
    Toy
    is added to
    toyList
    .


Answer

A RealmList is ordered, so case #1 is correct. Just add them in the order you want, and that order will be persisted.

In general though, ordering is not guaranteed, so creating 2 objects in the Realm does not imply an order:

realm.createObject(Person.class, 1);
realm.createObject(Person.class, 2);

// Doing this is not guaranteed to return Person:1
realm.where(Person.class).findAll().first()

// Always use a sort in queries if you want a specific order
realm.where(Person.class).findAllSorted("id", Sort.ASCENDING).first();
Comments