ionutzm05
ionutzm05

Reputation: 53

Android Search in ListView not working properly

I'm trying to add the search functionality to a ListView that has a custom adapter. When I type something in the EditText it searches and shows the results corectly but if I try to erase what I just wrote it won't come out with the initial list, it will stay with the already filtered list. Here is the code :

In MainActivity :

private TextWatcher searchTextWatcher = new TextWatcher() {
    @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)     {
              adapter.getFilter().filter(s.toString());
              adapter.notifyDataSetChanged();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int     after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

In LazyAdapter :

public Filter getFilter() {
    return new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            data = (ArrayList<HashMap<String, String>>) results.values;
            LazyAdapter.this.notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            ArrayList<HashMap<String, String>> filteredResults = getFilteredResults(constraint);

            FilterResults results = new FilterResults();
            results.values = filteredResults;

            return results;
        }
    };
}

protected ArrayList<HashMap<String, String>> getFilteredResults(
        CharSequence constraint) {
    ArrayList<HashMap<String, String>> filteredTeams = new ArrayList<HashMap<String, String>>();
    for(int i=0;i< data.size();i++){
        if(data.get(i).get(MainActivity.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase())){
            filteredTeams.add(data.get(i));
        }
    }

    return filteredTeams;
}

What is wrong with my code? Thank you!

Upvotes: 1

Views: 665

Answers (1)

dymmeh
dymmeh

Reputation: 22306

Realize that when you filter you are replacing your unfiltered results in your ArrayList with your filtered results. When you hit backspace to delete characters you are trying to now filter based on your already filtered list which is why your results won't change. You will need to keep a reference to your original data set that doesn't have any filter applied to it and always filter using that, but never change/replace it.

Upvotes: 4

Related Questions