首页 > 解决方案 > 用于大量记录的领域查询冻结应用程序

问题描述

我正在运行领域查询以检索参与者列表,之后我将单个参与者作为参数传递给方法 getCommunity(participant) 以获取参与者所属的区域。然后我继续将给定社区的所有参与者添加到列表中,以便在回收者视图中显示它们。下面是代码:

List<StoredParticipant> FilteredMembers = new ArrayList<>();
        Realm realm = Realm.getDefaultInstance();
        try {
            realm.executeTransaction(realm1 -> {
                RealmResults<StoredParticipant> participants = realm1.where(StoredParticipant.class).beginGroup()
                        .isNull("isDeceased")
                        .or()
                        .notEqualTo("isDeceased", true)
                        .endGroup().findAll();

                for (StoredParticipant storedParticipant : participants) {
                    String community = getCommunity(storedParticipant);
                    if (community.equalsIgnoreCase(Community)) {
                        FilteredMembers.add(storedParticipant);

                    }
                }
            });

        } catch (Exception e) {

        }

导致滞后的行是:
String community = getCommunity(storedParticipant);

我应该如何重写代码以防止滞后?

编辑: getCommunity() 的代码如下:

  public static String getCommunity(StoredParticipant participant) {
    String community = "";

    try (Realm realm = Realm.getDefaultInstance()) {
        HouseholdRelationship hhr = realm.where(HouseholdRelationship.class)
                .equalTo("participantId", participant.getId())
                .isNull("endDate")
                .findFirst();

        if (hhr != null) {
            Household household = realm.where(Household.class)
                    .equalTo("id", hhr.getHouseholdId())
                    .findFirst();

            if (household != null) {
                HouseholdAddress address = HouseholdService.getCurrentAddress(household);
                if (address != null) {
                    community = AreaService.getCommunityName(address.getArea());

                }
            }
        }
    }

    return community;
}

标签: androidrealm

解决方案


推荐阅读