合并多个RealmList并对结果列表进行排序?

时间:2017-05-21 07:17:01

标签: java android realm

我刚开始在我当前的Android应用程序中使用Realm,到目前为止它很棒。 不幸的是我遇到了一个问题:

在我的应用程序中,用户可以添加不同类型的条目(他今天吃了什么?他有什么饮料?等等)到他的日记中。 一个DiaryEntry对象表示给定日期所有条目的总和(例如,21.05.2017等)。

public class DiaryEntry extends RealmObject {

    // ID of the day this diary entry represents
    @PrimaryKey private Integer dateId;

    private RealmList<MealEntry> mealEntries;
    private RealmList<DrinkEntry> drinkEntries;
    private RealmList<SymptomEntry> symptomEntries;
    private RealmList<MedicineEntry> medicineEntries;

    public void addMealEntry(MealEntry mealEntry) {
        mealEntries.add(mealEntry);
    }
    public RealmList<MealEntry> getMealEntries() {
        return mealEntries;
    }

    public void addDrinkEntry(DrinkEntry drinkEntry) {
        drinkEntries.add(drinkEntry);
    }
    public RealmList<DrinkEntry> getDrinkEntries() {
        return drinkEntries;
    }

    public void addSymptomEntry(SymptomEntry symptomEntry) {
        symptomEntries.add(symptomEntry);
    }
    public RealmList<SymptomEntry> getSymptomEntries() {
        return symptomEntries;
    }

    public void addMedicineEntry(MedicineEntry medicineEntry) {
        medicineEntries.add(medicineEntry);
    }
    public RealmList<MedicineEntry> getMedicineEntries() {
        return medicineEntries;
    }
}

要在日记中显示特定日期的此数据,应按用户创建条目的时间对所有条目进行排序。 因此,每个条目对象都包含一个字段'time'。

private int time;

我想出了一个解决我问题的临时解决方案,但这远非完美。 以下代码在UI线程上执行,这显然是不好的做法。

List<RealmObject> entryList = new ArrayList<>();
        OrderedRealmCollectionSnapshot<MealEntry> mealEntries = diaryEntry.getMealEntries().createSnapshot();
        OrderedRealmCollectionSnapshot<DrinkEntry> drinkEntries = diaryEntry.getDrinkEntries().createSnapshot();
        OrderedRealmCollectionSnapshot<MedicineEntry> medicineEntries = diaryEntry.getMedicineEntries().createSnapshot();
        OrderedRealmCollectionSnapshot<SymptomEntry> symptomEntries = diaryEntry.getSymptomEntries().createSnapshot();

        entryList.addAll(mealEntries);
        entryList.addAll(drinkEntries);
        entryList.addAll(medicineEntries);
        entryList.addAll(symptomEntries);

        Collections.sort(entryList, entryComparator);

对条目列表进行排序的代码通过调用time字段的getter方法来使用反射:

public int compare(RealmObject entry1, RealmObject entry2) {
            try {
                Method timeGetter1 = entry1.getClass().getMethod("getTime");
                Method timeGetter2 = entry2.getClass().getMethod("getTime");

                int time1 = (Integer) timeGetter1.invoke(entry1);
                int time2 = (Integer) timeGetter2.invoke(entry2);

                return time1 - time2;
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                Timber.d("No such method 'getTime'.");
           }
      // Other catch clauses

正如我之前所说,所有这些都发生在UI线程上。

我知道我无法通过线程传递RealmObject s,RealmListRealmResult,因此我真的很难为此提出异步解决方案。我想到了一个后台线程,并在那里创建RealmList对象内所有DiaryEntry的副本。然后合并这个非托管列表并对其进行排序 - 所有这些都在后台线程中。

所以我的问题:是否有任何首选策略可以合并多个RealmList并对合并列表进行排序 - 所有这些都是以异步方式进行的?我上面描述的尝试会起作用吗?

1 个答案:

答案 0 :(得分:1)

谢谢@EpicPandaForce

我完全按照你所描述的方式解决了它,它就像一个魅力 - 现在我甚至拥有实时功能,无需手动刷新数据,很好:)

如果有人遇到同样的问题,我会在这里发布一些代码片段,说明我是如何在代码中解决的。

public class Entry extends RealmObject {
    private static final int ENTRY_MEAL = 0;
    private static final int ENTRY_DRINK = 1;
    private static final int ENTRY_SYMPTOM = 2;
    private static final int ENTRY_MEDICINE = 3;

    /** The tag describes what kind of entry it represents */
    private int tag;

    /* Only one of these can be set, according to what this entry represents. */
    @Nullable private MealEntry mealEntry;
    @Nullable private DrinkEntry drinkEntry;
    @Nullable private SymptomEntry symptomEntry;
    @Nullable private MedicineEntry medicineEntry;

    /** The time value this entry was created at */
    /** Format: hours + minutes * 60 */
    private int time;

    public int getTime() {
        return time;
    }

/* Can only be accessed from within the 'data' package */

    void setTime(int time) {
        this.time = time;
    }

/**
     * Creates a new entry object in the realm database and tags it as 'MEAL'
     *
     * @param realm not null
     * @param mealEntry the {@link MealEntry} object to map this entry to, not null
     *
     * @return the newly created entry
     */
    static Entry createEntryAsMeal(@NonNull final Realm realm, @NonNull final MealEntry mealEntry) {
        if(realm == null) {
            throw new IllegalArgumentException("'realm' may not be null");
        }
        if(mealEntry == null) {
            throw new IllegalArgumentException("'mealEntry' may not be null");
        }

        Entry entry = realm.createObject(Entry.class);
        entry.tag = ENTRY_MEAL;
        entry.mealEntry = mealEntry;
        return entry;
        }

/* Same methods for other tag types ... */

在MealEntry.class中:

public class MealEntry extends RealmObject {

    @PrimaryKey @Required private String id;

    @Required private String title;

    /** The entry objects this meal-entry is added to */
    Entry entry;

    /** This time value describes when the user consumed this meal **/
    private int time;
// other fields

/**
* Creates a new MealEntry object in the realm.
 * <p>
 *     Note: It is important to use this factory method for creating {@link MealEntry} objects in realm.
 *     Under the hood, a {@link Entry} object is created for every MealEntry and linked to it.
 * </p>
 *
 * @param realm not null
 *
 * @return new MealEntry object which has been added to the <code>realm</code>
 */
public static MealEntry createInRealm(@NonNull Realm realm) {
    if(realm == null) {
        throw new IllegalArgumentException("'realm' may not be null");
    }

    MealEntry mealEntry = realm.createObject(MealEntry.class, UUID.randomUUID().toString());
    mealEntry.entry = Entry.createEntryAsMeal(realm, mealEntry);
    return mealEntry;
}

“时间”字段存在于Entry.class和MealEntry.class中,因此如果后者更改,则必须相应地更新条目:

/**
     * Sets the time value for the <code>mealEntry</code> to the specified value.
     * <p>
     *     Note: This method is necessary in order to sync the new time value with the underlying
     *     {@link Entry} object that is connected with the <code>mealEntry</code>.
     * </p>
     *
     * @param mealEntry the {@link MealEntry} object to set the time for, not null
     *
     * @param time the new time value, must be in range of [0, 24*60] because of the format: hours*60 + minutes
     *
     */
    public static void setTimeForMealEntry(@NonNull MealEntry mealEntry, @IntRange(from=0, to=24*60) int time) {
        if(mealEntry == null) {
            throw new IllegalArgumentException("'mealEntry' may not be null");
        }

        mealEntry.setTime(time);

        Entry entry = mealEntry.entry;
        if(entry == null) {
            throw new IllegalStateException("'mealEntry' contains no object of type 'Entry'! Something went wrong on creation of the 'mealEntry'");
        }

        /* Syncs the entries time value with the time value for this MealEntry. */
        /* That´s important for sorting a list of all entries. */
        entry.setTime(time);
    }

注意:我只能在MealEntry中存储相应Entry对象的ID,反之亦然,Entry对象将ID存储到相应的MealEntry对象。但是,我不知道这样做的性能有何不同,所以我采用了上述方法。 另一种方法的一个原因是我不必将'time'字段存储两次,一次存入Entry.class,一次存放在MealEntry.class中,因为在Entry.class中我可以得到时间通过ID找到相应的MealEntry对象,然后获取时间。