Home » Android » android – Constraint on performFiltering returns null on first character

android – Constraint on performFiltering returns null on first character

Posted by: admin May 14, 2020 Leave a comment

Questions:

I wrote a custom Filter for an AutoCompleteTextView.
It works fine, but one small thing. The Constraint on performFiltering is null on the first character. Meaning the filtering process starts only when the second character is put into the AutoCompleteTextView.

This is the code of the Filter:

private Filter nameFilter = new Filter() {
    public String convertResultToString(Object resultValue) {
        String fullName = ((User)(resultValue)).facebookName; 
        return fullName;
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        if(constraint != null) {
            suggestions.clear();
            for (User friend : allFriends) {
                if(friend.facebookName.toLowerCase().contains(constraint.toString().toLowerCase())){
                    suggestions.add(friend);
                }
            }
            FilterResults filterResults = new FilterResults();
            filterResults.values = suggestions;
            filterResults.count = suggestions.size();
            return filterResults;
        } else {
            return new FilterResults();
        }
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        ArrayList<User> filteredList = (ArrayList<User>) results.values;
        if(results != null && results.count > 0) {
            clear();
            for (User friend : filteredList) {
                add(friend);
            }
            notifyDataSetChanged();
        }

    }
};

Can anyone help me how to fix this, so the Filter starts filtering on the first character?

How to&Answers:

Set the threshold to 1:

autoCompleteTextView.setThreshold(1)

Specifies the minimum number of characters the user has to type in the
edit box before the drop down list is shown. When threshold is less than or equals 0, a threshold of 1 is applied.