Skip to content
Advertisement

How to filter a listview using SearchView

I am using searchView to filter my list view. But the problem is only when I write the full element name then only the list is filtered. For example: I have a list of users – {“Bob”, “John”, “James”}. If I write J in searchView I want both John and James to be seen. But I get a Toast that this name is not in the list. Please help.

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            if (users.contains(query)){
                arrayAdapter.getFilter().filter(query);
            } else {
                Toast.makeText(ChatListActivity.this, "There is no user with this username, please search again.", Toast.LENGTH_SHORT).show();
            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            if (users.contains(newText)){
                arrayAdapter.getFilter().filter(newText);
            } else {
                Toast.makeText(ChatListActivity.this, "There is no user with this username, please search again.", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

Answer

Please try using a FilterListener like this

@Override
public boolean onQueryTextChange(String query) {
    Filter.FilterListener listener = new Filter.FilterListener() {
        @Override
        public void onFilterComplete(int count) {
            // conditions to check whether your list is empty
        }
    };
    newsListAdapter.getFilter().filter(query, listener);
    return false;
}
Advertisement