Search code examples
javarealmrealm-list

Creating managed RealmList outside RealmObject


In my app, I have a method that accepts an ArrayList of ID's and returns a RealmList of Machines belonging to these IDs.

public RealmList<Machine> getMachinesById(ArrayList<Long> machineIds) {
    RealmList<Machine> machines = new RealmList<Machine>();
    for (int i = 0; i < machineIds.size(); i++){
        Machine m = getMachineById(machineIds.get(i));
        if (m != null) {
            machines.add(m);
        }
    }
    return machines;
}

The getMachineById() function just finds the correct machine for a specific id.

I want to filter this output some more, however, when I try to get the RealmQuery by doing .where(), I get an Exception telling me I should put this RealmList in 'managed mode'.

Caused by: io.realm.exceptions.RealmException: This method is only available in managed mode
                                                 at io.realm.RealmList.where(RealmList.java:425)

I'm aware that I get this error because this list is standalone, and not managed by Realm.

It is probably important to add that this function will be called quite a lot, since it is triggered every time some list in my app refreshes. This would mean that (if possible) every time I'm creating a new managed RealmList.

My questions:

  • Is there any way to let this RealmList be managed by Realm?
  • If this is possible, is it a problem that this function is being called pretty often
  • Is there any other (preferred) way to achieve this (List of IDs > RealmResults/RealmQuery)

Solution

  • Is there any way to let this RealmList be managed by Realm?

    Yes. There is. But the point of having RealmList is it should be a field of an RealmObjects. eg.:

    public class Factory {
        RealmList<Machine> machineList;
        // setter & getters
    }
    
    Factory factory = new Factory();
    RealmList<Machine> machineList = new RealmList<>();
    // Add something to the list
    factory.setMachines(machineList);
    realm.beginTransaction();
    Factory managedFactory = realm.copyToRealmOrUpdate(factory);
    realm.commitTransaction();
    

    Managed means it has be persisted Realm.

    If this is possible, is it a problem that this function is being called pretty often

    Depends, if you don't need to persist them again, see answer 3.

    Is there any other (preferred) way to achieve this (List of IDs > RealmResults/RealmQuery)

    In your case, maybe you can use ReaulResults instead? eg.:

    RealmQuery<Machine> query = realm.where(Machine.class);
    for (int i = 0; i < machineIds.size(); i++){
        if (i != 0) query = query.or();
        query = query.equalTo("id", machineIds.get(i));
    }
    RealmResults<Machine> machines = query.findAll();