Search code examples
javaandroidandroid-studioautocompletetextview

AutoComplete TextView Android. Complete with first letters


The adapter that I have in the autoCompleteTextView is something like this:

  • -apple -pear -orange -banana -grape

The way it's working now if I type "p", in the dropDown list will appear apple, pear and grape because they make a match but I just want it to show pear because is the only word which starts with p. So, the question is: How can I tell the autoComplete's dropDownList to show matches with the words that start with what I'm searching on and not show words that contains it in some other position that is not the first. For example, if I type "pe" I want to show only pear and not grape because pear starts with that string. This is my code

ArrayList<String> data = dbHelper.getDataAsString();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, data);
autoCompleteTv.setAdapter(adapter);
autoCompleteTv.setThreshold(2);

Solution

  • Take this as a reference. I just tested this code after making, it should work fine.

    Assume your list was of only type strings.

    private String[] searchableList = {"apple", "pear", "grape"};
    

    I made this function which takes query and returns newly formatted list of strings.

        private List<String> filterQuery(String query) {
            // This takes all strings items which are valid with query
            List<String> filterList = new ArrayList<>();
            
            // Looping into each item from the list
            for (String currentString : searchableList) {
                // Make sure everything is lower case.
                String myString = currentString.toLowerCase(Locale.getDefault());
                // Take first two characters from the string, you may change it as required.
                String formatTitle = myString.substring(0, 2);
                // If query matches the current string add it to filterList
                if (formatTitle.contains(query)) {
                    filterList.add(formatTitle);
                }
            }
            return filterList;
        }
    

    Let me know how it goes.