Home > other >  Implementing SearchView for a RecyclerView that doesn't use a model class
Implementing SearchView for a RecyclerView that doesn't use a model class

Time:12-16

I've been trying to implement a SearchView for my RecyclerView that contains the list of all registered Firebase user. I've searched everywhere for tutorials that teaches how to use SearchView but all of them utilizes a model class. The problem is, what I created doesn't have one. I only utilize List<String>. Is it even possible?

CodePudding user response:

In activity class, initialize the SearchView and set an OnQueryTextListener to listen for changes to the query text:

SearchView searchView = findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        // Create a new list to store the filtered strings
        List<String> filteredList = new ArrayList<>();

        // Loop through the original list of strings and add only those
        // that contain the search query to the filtered list
        for (String s : originalList) {
           if (s.toLowerCase().contains(newText.toLowerCase())) {
               filteredList.add(s);
    }
}

        // Update the RecyclerView with the filtered list
        recyclerView.setAdapter(new YourAdapter(filteredList));
        return false;
    }
});

I hope this helps.

  • Related