Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter text in a ListView properly?

I've tried to filter my ListView from my EditText box, but currently, it's not working.

I have a ListView that get data properly and they are added to my own ListView using a ArrayAdapter class and my own ArrayList class. When I for example, typing in "table" I want it to sort from the loaded titles in my ListView and than it should show me the items that are left and matching table.

My current code:

private ArrayList<Order> orders; /* ArrayList class with my own Order class to 
define title, info etc. */
private OrderAdapter adapter; //Own class that extends ArrayAdapter

orders = new ArrayList<Order>();
adapter = new OrderAdapter(this, R.layout.listrow, orders); /* listrow defining a
single item in my ListView */
setListAdapter(adapter); //Set our adapter to a ListView

search.addTextChangedListener(filterTextWatcher); //search is my EditText

private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        adapter.getFilter().filter(s); //Filter from my adapter
        adapter.notifyDataSetChanged(); //Update my view
    }

};

Okay, so how can I achieve this? When I entering some value into the EditText box everything disappear, even if there is a match.

Thanks in advance and tell me if you need more code snippets or if this question i unclear!

like image 487
Curtain Avatar asked Oct 05 '10 06:10

Curtain


1 Answers

The built-in filter implemented by ArrayAdapter converts the contained object to string by calling toString() method. It is this string that will be used to perform the matching. If you are only trying to match one string field in your Order object, you can override the toString() method for your Order class to return that field. If you want to perform more flexible matching, such as matching multiple fields, check out this post which shows how to create a custom filter:

Custom filtering in Android using ArrayAdapter

like image 185
onlygo Avatar answered Sep 19 '22 16:09

onlygo