1

I am currently using an AutoCompleteTextView with a list of terms that gives suggestions as a user is typing. However, I want to use a different string algorithm than simply checking if a string contains your search term, that compares how close two strings are (e.g. searching "chcken" should show "chicken").

I have produced a method that takes a string parameter - your search query - and returns a sorted array of strings in the database that match that query based on relevance. How do I let the AutoCompleteTextView use that array? I can't simply attach it to the adapter with every keystroke, because that doesn't change the inherent behavior of the AutoCompleteTextView for only showing elements inside the array that MATCH the string query.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Joe Balin
  • 177
  • 2
  • 17

1 Answers1

1

You can implement a custom filter in your adapter.

Example:

public class MyFilterableAdapter extends ListAdapter<String> implements Filterable {

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            public String convertResultToString(Object resultValue) {
                return (String) resultValue;
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                filterResults.values = filteredArray;
                filterResults.count = filteredArray.size();
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    //here you will need to update the array where you are controlling what shows in the list
                    notifyDataSetChanged();
                }
            }
        };
    }
}

Since you did not provided any code, I don't know what adapter you are using, but you will need to implement all the adapter method (getCount, getView, etc).

You can find more info in those questions:

How to create custom BaseAdapter for AutoCompleteTextView

Autocompletetextview with custom adapter and filter

jonathanrz
  • 4,206
  • 6
  • 35
  • 58
  • 1
    Thanks! This helped a lot. I now have a working custom adapter, but I'm still quite nooby with Android and each entry on my autocomplete drop down menu shows another copy of the search bar... probably because I inflated the whole fragment with view = inflater.inflate(R.layout.fragment_search, viewGroup, false). What am I supposed to be inflating here, and where should I set the text in getView? – Joe Balin Dec 03 '17 at 01:25
  • 1
    EDIT: Fixed it all. Thanks again for helping me get started – Joe Balin Dec 03 '17 at 01:35