I have a recycler view with flight information, and I am searching using the flight number on the search bar. When I search, the recyclerview is updated dynamically for which the logic is there in my filter function, however when I clear the search, the recycler view is completely empty. How can I fix this issue?
search filter function
private void filter(String text) {
ArrayList<FlightItem> filteredList = new ArrayList<>();
for(FlightItem item : flightItems) {
if(item.getFlightNumber().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
flightItems.clear();
flightItems.addAll(filteredList);
}
}
keep a copy of flightItems
, as you are clearing it before adding filtered items
ArrayList<FlightItem> flightItems = new ArrayList<>();
ArrayList<FlightItem> flightItemsCopy = new ArrayList<>();
private void filter(String text) {
if(text.trim() == ""){
clearSearch()
return
}
ArrayList<FlightItem> filteredList = new ArrayList<>();
for(FlightItem item : flightItems) {
if(item.getFlightNumber().toLowerCase().contains(text.toLowerCase())){
filteredList.add(item);
}
}
flightItemsCopy.clear(); //clear copy
flightItemsCopy.addAll(flightItems); // make a copy here
mAdapter.filterList(filteredList);
flightItems.clear();
flightItems.addAll(filteredList);
}
}
private void clearSearch(){
flightItems.clear();
flightItems.addAll(flightItemsCopy);
mAdapter.notifyDataSetChanged();
}