Search code examples
androidandroid-arrayadapterhashsetautocompletetextview

Preventing AutoCompleteTextView from showing duplicates


Take a look at my code below:

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);

I tried this approach to prevent duplicate items in my ACTV(AutoCompleteTextView). However, suggestions no longer appear. It did work when I didn't first add the retrieved data and store it in hashSet and then add it to autoComplete but instead directly adding it to autoComplete.

How can I solve this?


Edit: I've noticed something, in the method where I'm retrireving my data...

 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);
                }
            }

...my HashSet gets filled with items. However, when the program EXITS that method, it seems that my HashSet is completely CLEARED. What I mean is, in the onDataChange() method, when I add:

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

I get the list of items normally as I expected. However, when I do the for loop OUTSIDE onDataChange(), the HashSet is empty, meaning it was cleared. However, this is not the same when using ArrayAdapter


Solution

  • After hours of research and thinking, I did it.

    After you've gotten your data, before added anything to your ArrayAdapter remove all strings that are the same as the one you just got first, THEN add it. This pretty much says:

    "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.

    Here's the example code:

    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);
    }
    

    The above code says: Find all the s in the ArrayAdapter and remove them, then, add a single s. That way, I only have 1 s. (Relate this to the KitKat example above).