Search code examples
javaandroidandroid-recyclerviewsearchviewandroid-cardview

How to refresh my RecyclerView list when searchview is cleared?


When a Search query text is entered, I filter my card items in the RecyclerView and display them on top. However, when all the text is cleared, for some reason, the list does not go back to the original state. How to refresh my RecyclerView list? The code below should give you a better idea.

@Override
    public boolean onQueryTextChange(String newText) {
        final List<Number> filteredModelList = filter(numbers, newText);
        Log.v("App", newText + ", " + numbers.size() + ", " + filteredModelList.size());
        adapter.animateTo(filteredModelList);
        list.scrollToPosition(0);
        adapter.notifyDataSetChanged();
        if (newText.equalsIgnoreCase("")){
            try{
                Log.e("SEARCH VIEW", "I CAN ENTER HERE"); //But the list doesn't refresh
                adapter.animateTo(numbers);
                adapter.notifyDataSetChanged();
                list.setAdapter(adapter);
                list.scrollToPosition
            } catch(Exception e){
                Log.e("Caught Exception", e.toString());
            }

        }
        return true;
    }

This is problematic when no item matched the search - then the screen is just blank with no cards, and the "X" button on the SearchView is not visible either. When the X is visible, and I touch it, the list goes back to its original state. As a second question, is there a way to always display the close icon ("X")?


Solution

  • Remember you have a method which loads data into your RecyclerView, so what you do, you call back again that method in the IF statement, like : when the newTextlength is equal to zero , Do something ......

    Below is the algorithm : .

    if (newText.length() == 0){    
        //Reload the data Again , use the existing  method you have of loading data in the RecyclerView .
    }
    

    If you have some problems , just post again your code loading data in the RecyclerView and I show it to you again.