防止 AutoCompleteTextView 显示重复项

Preventing AutoCompleteTextView from showing duplicates

看看下面我的代码:

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
final ArrayAdapter<String> autoComplete = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
final HashSet<String> hashSet = new HashSet<>();
      //*I cut out the part where I get the data from the database and store it into "hashSet"
autoComplete.addAll(hashSet);
actv.setAdapter(autoComplete);

我试过这种方法来防止我的 ACTV 中出现重复项 (AutoCompleteTextView)。但是,建议不再出现。当我 没有 首先添加检索到的数据并将其存储在 hashSet 然后将其添加到 autoComplete 而是直接将其添加到 autoComplete.

我该如何解决这个问题?


编辑: 我在检索数据的方法中注意到了一些事情...

 hashSet = new HashSet<>();
        database.child("AutoCompleteOptions").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()) {
                    String suggestion = suggestionSnapshot.child("suggestion").getValue(String.class);
                        //Log.d("FBSA",suggestion);
                        hashSet.add(suggestion);
                        for(String s:hashSet)
                            Log.d("FBSA",s);
                }
            }

...我的 HashSet 装满了物品。但是,当程序退出该方法时,我的 HashSet 似乎已完全清除。我的意思是,在 onDataChange() 方法中,当我添加:

for(String s:hashSet)
   Log.d(TAG,s)

如我所料,我可以正常获取项目列表。 但是,当我在onDataChange()外部执行for循环时,HashSet是空的,这意味着它被清除了。 但是,这和使用ArrayAdapter

不一样

经过几个小时的研究和思考,我做到了。

获得数据后,在向 ArrayAdapter 添加任何内容之前删除所有与刚获得的字符串相同的字符串,然后添加它。这几乎是在说:

"You gave me a KitKat bar? Ok, let me see if I have any KitKat bars, if I do, I'll throw them all out except for the one you're giving me, that way I'll only have one.

示例代码如下:

for(String s:myData){
  //This removes all strings that are equal to s in the adapter
  for(int i=0;i < adapter.getCount();i++){
     if(adapter.getItem(i).equals(s)
          adapter.remove(s)
   }
//Now that there are no more s in the ArrayAdapter, we add a single s, so now we only have one
adapter.add(s);
}

上面的代码说:找到ArrayAdapter中的所有s并删除它们,然后添加一个s。这样,我只有 1 s。 (将此与上面的 KitKat 示例联系起来)。

运行 进入同样的问题。我想我找到了更好的方法。我知道这是旧的,只是分享给下一个人。

for (String s: myData) { 
     if (!adapter.contains(s.getName().toLowerCase)) {
         adapter.add(s.getName());
         }
    }