Timon Devos
Timon Devos

Reputation: 443

Android filter listview with edittext

I have a listview with products in it. I override the tostring method of the products:

    @Override
    public String toString() {
        return this.getNaam();
    }

I add addTextChangedListener to my EditText.

tvZoek.addTextChangedListener(new TextWatcher() {               
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString().toLowerCase());             
        }
        public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
        }
        public void afterTextChanged(Editable s) {
        }
});

When I do a search the list is filtered. But for example if I search for "Bio" and there are 5 product in the list with "Bio" in their name, than it is showing first 5 products in the list, not the 5 products with "Bio" in their name.

I didn't override the getFilter() method in the adapter.

How do I show the correct products? (I'm working with ArrayAdapter)

Upvotes: 0

Views: 804

Answers (1)

Jayabal
Jayabal

Reputation: 3619

try the following.

  public void onTextChanged(CharSequence s, int start, int before, int count) {
                    updateList(s.toString);             
                }


public void updateList(String filter) {

List<> tempList = new ArrayLsit<>();

int yourListSize = myList.count();
for (int i = 0; i < myListSize; i++) {
if (filter != null) {
   if (myList.get(i).contains(filter)) {
    tempList.add(myList.get(i));
  }
 }
}

// create adapter using tempList
// setAdapter

}

Upvotes: 1

Related Questions