【问题标题】:Failed To Remove Duplicate Value From Android ArrayList无法从 Android ArrayList 中删除重复值
【发布时间】:2019-05-31 16:16:07
【问题描述】:

我有一个 firebase 数据库,所以我进行了查询以根据标签查询获取图像。但是从数据库中获取数据后,当我尝试将其添加到数组列表中时。我给了我重复的价值。我不知道这是firebase问题还是java问题。 image0 和 image 1 被添加了两次。我曾尝试使用 Hashset 清除重复值。另一个奇怪的是循环只迭代了两次,我用计数器检查过。

private void searchInWallpapers(){
    Query wallpaperquery = myRef.child("wallpapers").orderByChild("tag").equalTo(keyWord);
    wallpaperquery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int i = 0;
            for (DataSnapshot eachImage : dataSnapshot.getChildren()) {
                ImageModelClass  data2 = new ImageModelClass(eachImage.child("imgUrl").getValue().
                        toString(),eachImage.child("like").getValue().toString(),eachImage.child("title").getValue().toString());
                resultList.add(data2);

            }

            Set<ImageModelClass> set = new HashSet<>(resultList);
            resultList.clear();
            resultList.addAll(set);
            imageListAdapter imageListAdapter = new imageListAdapter(search_result.this,resultList);
            resultRecycler.setAdapter(imageListAdapter);
            FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(search_result.this);
            layoutManager.setJustifyContent(JustifyContent.SPACE_AROUND);
            layoutManager.setFlexDirection(FlexDirection.ROW);
            resultRecycler.setLayoutManager(layoutManager);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

【问题讨论】:

  • '循环只迭代两次',你的图中只有两个节点,所以循环两次是对的,不是吗?
  • 是的,它应该迭代两次,但为什么要添加两次数据。

标签: java android arraylist firebase-realtime-database


【解决方案1】:

您似乎正在将数据添加到列表“resultList”中而没有清除它

你需要添加类似的代码

if (resultList == null)
        resultList = new ....
    else
        resultList.clear();

    int i = 0;
    for (DataSnapshot eachImage : dataSnapshot.getChildren()) {
        ImageModelClass data2 = new ImageModelClass(eachImage.child("imgUrl").getValue().
                toString(), eachImage.child("like").getValue().toString(), eachImage.child("title").getValue().toString());
        resultList.add(data2);
    }

那么不需要处理删除重复值

【讨论】:

  • 不,我无法清除数据,因为我正在从不同节点添加来自 firebase 的数据,在这种情况下数据不会重复。仅在这种情况下意味着 searchInWallpaer 方法数据在数组列表中重复。很奇怪的事情。
  • 您注册查询的侦听器可能会在数据更改时被多次调用,当数据更改方法触发时可能会调用多个值,只需确认一个
  • 其实我是在另一个valueeventlistener的datachange方法下调用searchInWallpaper方法
猜你喜欢
  • 2014-03-25
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 2015-12-12
相关资源
最近更新 更多