【问题标题】:Android SortedList remove method is skipping itemsAndroid SortedList remove 方法正在跳过项目
【发布时间】:2018-08-24 18:10:29
【问题描述】:

我在 RecyclerView 中遇到了 Android SortedList 的问题,主要是 remove 方法:
公共无效替换所有(列出userFertList,列出defaultFertList){ restartIndexes(userFertList, defaultFertList); mComparator.swapLists(Utils.fertiliserListToNameList(userFertList));

    List<Fertiliser> combinedList = Utils.combineFertLists(userFertList, defaultFertList);

    mSortedList.beginBatchedUpdates();
    for (int i = mSortedList.size() -1; i > -1 ; i--) {
        final Fertiliser fertiliser = mSortedList.get(i);
        if(!combinedList.contains(fertiliser)){
            if(!mSortedList.remove(fertiliser)){
                throw new RuntimeException();
            };
        }
    }

    mSortedList.addAll(combinedList);
    mSortedList.endBatchedUpdates();
}

上面的代码是在过滤列表的时候执行的。新列表中不存在的所有对象都将被删除。但是,删除对象的调用有时会失败。我知道该对象存在,因为它取自 SortedList 本身。

我的研究表明我的 Comparator 比较方法有问题:

        @Override
    public int compare(Fertiliser fertiliser, Fertiliser t1) {
        if(fertiliser == t1){
            return 0;
        }

        if(mUserFertNames.contains(fertiliser.getName()) != mUserFertNames.contains(t1.getName())){
            return mUserFertNames.contains(fertiliser.getName()) ? -1 : 1;
        } else {
            return fertiliser.getName().compareToIgnoreCase(t1.getName());
        }
    }

我按两个标准排序(一个检查对象是否存在于列表中和按名称)。

所以我的想法是,因为 SortedList 使用 Comparator 来定位元素,我的 Comparator 给出了错误的结果,并且列表找不到该项目: 从 SortedList 调用的方法:

    private int findIndexOf(T item, T[] mData, int left, int right, int reason) {
    while (left < right) {
        final int middle = (left + right) / 2;
        T myItem = mData[middle];
        final int cmp = mCallback.compare(myItem, item);
        if (cmp < 0) {
            left = middle + 1;
        } else if (cmp == 0) {
            if (mCallback.areItemsTheSame(myItem, item)) {
                return middle;
            } else {
                int exact = linearEqualitySearch(item, middle, left, right);
                if (reason == INSERTION) {
                    return exact == INVALID_POSITION ? middle : exact;
                } else {
                    return exact;
                }
            }
        } else {
            right = middle;
        }
    }
    return reason == INSERTION ? left : INVALID_POSITION;
}

但是我找不到解决方案。你能帮帮我吗?

附:当我检查错误时,两个对象都不在列表中(因此它们仅按名称进行比较)。

【问题讨论】:

  • 这个问题没有答案? :) 。我有类似的问题。没有人知道答案吗? :)

标签: android android-recyclerview comparator sortedlist


【解决方案1】:

尝试 .removeItemAt(i) 而不是 .remove(fertiliser)。这在过滤列表时对我有用。

【讨论】:

  • 请将其表述为有条件的解释性答案,以避免给人以澄清问题而不是回答的印象(应该使用评论而不是答案,比较meta.stackexchange.com/questions/214173/…)。例如像“如果你的问题是......那么解决方案是......因为......。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 2015-01-04
  • 2019-02-12
  • 1970-01-01
  • 2015-10-29
  • 2014-03-24
相关资源
最近更新 更多