How to filter with edit text with FirebaseRecyclerAdapter in android using kotlin

Viewed 230

Anyone please help me to use editText with FireBaseRecyclerAdapter to filter the search. Sorry, Iam a beginner in android and kotlin. I have an activity associate with editText and recyclerview, and at the begin activity, it display all objects. The problem here is how to use edit text to filter search the object inside the recyclerview based on name?

1 Answers

I am assuming here that your object is 'Car' Create a method that filters the cars by its name and returns the list of cars.

public static List<Car> filterCars(List<Car> cars, String searchText) {
    List<Car> filteredCars = new ArrayList<>();
        Car c;
        for(int i = 0; i < cars.size(); i++) {
            c = cars.get(i);
            if (c.getCarName().toLowerCase().contains(searchText.trim().toLowerCase())) {
                filteredCars.add(c);
            }
        }
        return  filteredCars;
}

This function accepts list of cars as an input and a string to search in the car's name and returns the list of cars matching the name of the car with the searchText.

Now, in activity, in the EditText where you type the search text, add TextchangeListener.

yourEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            //grab your list to display in recyclerview.
            // suppose it is carList
            List<Car> newList = filterCars(YourListOfCar, editable.toString().trim());
            
           // now this newList contains filtered car's list
           // now send it to the adapter and call adapter function
           // notifyDataSetChanged()
        }
    }
});
Related