filipp.kowalski
filipp.kowalski

Reputation: 5605

Simple search filtering in Android listView

I want to add simple search filter in my Android ListView just like here :

Search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {

            MainActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
    });

This code is from tutorial found in the internet (I have lost an url). It is based on ArrayAdapter but in my class I am using SimpleCursorAdapter and this code doesn't work. I mean I can type but it won't filter search results. Here is my code :

// Create the pointer to the desired data
        dataAdapter = new SimpleCursorAdapter(
                this, R.layout.contact_row, contactsCursor, columns, to, 0);
        ListView listView = (ListView) findViewById(R.id.list);
        Search = (EditText) findViewById(R.id.inputSearch); 

        Search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {

                ContactListActivity.this.dataAdapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });

Is there any way to set this filter function on SimpleCursorAdapter?

Upvotes: 0

Views: 2294

Answers (1)

SemaphoreMetaphor
SemaphoreMetaphor

Reputation: 691

Search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {
            String where = *YOURCOLUMN* + " LIKE '%" + cs + "%'";

            Cursor c = db.query(*TABLE*, *COLUMNS*, where, null, null, null, null);

            dataAdapter.swapCursor(c);
            dataAdapter.notifyDataSetChanged();
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
});

Obviously your gonna need to put in your own data, but for the most part that should do what you want. Hope it works out!

Upvotes: 4

Related Questions