gpt4 book ai didi

java - 在 RealmObject 外部创建托管 RealmList

转载 作者:行者123 更新时间:2023-11-30 07:23:25 25 4
gpt4 key购买 nike

在我的应用中,我有一个方法接受 ID 的 ArrayList 并返回属于这些 ID 的机器的 RealmList

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;
}

getMachineById() 函数只是查找特定 ID 的正确机器。

我想进一步过滤此输出,但是,当我尝试通过执行 .where() 获取 RealmQuery 时,我收到一个异常,告诉我应该将此 RealmList 置于“托管模式”。

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

我知道收到此错误是因为此列表是独立的,并且不受 Realm 管理。

可能需要补充的是,此函数将被多次调用,因为每次我的应用程序中的某些列表刷新时都会触发它。这意味着(如果可能的话)每次我创建新的托管 RealmList 时。

我的问题:

  • 有什么办法让这个RealmList由Realm来管理吗?
  • 如果这是可能的,那么频繁调用此函数是否存在问题
  • 是否有任何其他(首选)方法来实现此目的(ID 列表 > RealmResults/RealmQuery)

最佳答案

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

是的。有。但拥有 RealmList 的要点是它应该是 RealmObjects 的字段。例如:

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();

托管表示已持久化Realm。

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

视情况而定,如果您不需要再次保留它们,请参阅答案 3。

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

就您而言,也许您可​​以使用 ReaulResults 代替?例如:

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();

关于java - 在 RealmObject 外部创建托管 RealmList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37162444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com