Filtering with CursorAdapter
suggest change// Get the reference to your ListView
ListView listResults = (ListView) findViewById(R.id.listResults);
// Set its adapter
listResults.setAdapter(adapter);
// Enable filtering in ListView
listResults.setTextFilterEnabled(true);
// Prepare your adapter for filtering
adapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence constraint) {
// in real life, do something more secure than concatenation
// but it will depend on your schema
// This is the query that will run on filtering
String query = "SELECT _ID as _id, name FROM MYTABLE "
+ "where name like '%" + constraint + "%' "
+ "ORDER BY NAME ASC";
return db.rawQuery(query, null);
}
});
Let’s say your query will run every time the user types in an EditText
:
EditText queryText = (EditText) findViewById(R.id.textQuery);
queryText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
}
@Override
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
// This is the filter in action
adapter.getFilter().filter(s.toString());
// Don't forget to notify the adapter
adapter.notifyDataSetChanged();
}
@Override
public void afterTextChanged(final Editable s) {
}
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents