Reputation: 8261
I have a ListView and a EditText. How can I filter ListView data when typing on EditText ?
My code is given below:
public class ListContacts extends ListActivity {
ListAdapter lAdapter;
EditText filterText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Associate the xml with the activity
setContentView(R.layout.activitylist);
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null,
null, null,
null);
startManagingCursor(cursor);
// start mappings
String[] columns = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
int[] names = new int[] { R.id.contact_name };
lAdapter = new ImageCursorAdapter(this, R.layout.main, cursor, columns,
names);
/** * to filter contacts */
filterText = (EditText) findViewById(R.id.EditText01);
filterText.addTextChangedListener(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) {
}
});
}
}// end of class ListContacts
public class ImageCursorAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
public ImageCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
public View getView(int pos, View inView, ViewGroup parent) {
}
}// end of class ImageCursorAdapter
Upvotes: 1
Views: 2896
Reputation: 8261
srchBox = (EditText) this.findViewById(R.id.searchTxt);
String srchName = srchBox.getText().toString();
srchBox.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
System.out.println("TExt changed");
String srchName = srchBox.getText().toString();
System.out.println(srchName);
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts.HAS_PHONE_NUMBER
+ " = 1 AND "
+ ContactsContract.Contacts.DISPLAY_NAME
+ " like " + "'" + srchName + "%'",
null,
"UPPER(" + ContactsContract.Contacts.DISPLAY_NAME
+ ") ASC");
startManagingCursor(cursor);
Load(cursor);
}
/*
* for loading after search entered
*/
public void Load(Cursor cursor) {
// start mappings
String[] columns = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
int[] names = new int[] { R.id.contact_name };
lAdapter = new ImageCursorAdapter(this, R.layout.main, cursor, columns,
names);
checkBox = (CheckBox) findViewById(R.id.bcheck);
setListAdapter(lAdapter);
}
Upvotes: 2