I have an edittext and a listview in my application my listview show contact list. I want listview filter with edittext. I searched a lot on google and found some examles but none worked for me here's my code
my custom adapter
public class ContactListAdapter extends ArrayAdapter {
private final Activity activity;
private final List<ContactStock> stocks;
private ArrayList<ContactStock> arraylist;
public ContactListAdapter(Activity activity, List<ContactStock> objects) {
super(activity, R.layout.listview_detail, objects);
this.activity = activity;
this.stocks = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
ContactStockView sv = null;
if (rowView == null) {
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(
R.layout.listview_detail, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sv = new ContactStockView();
sv.name = (TextView) rowView.findViewById(R.id.textView1);
sv.number = (TextView) rowView.findViewById(R.id.textView2);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sv);
} else {
sv = (ContactStockView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
ContactStock currentStock = (ContactStock) stocks.get(position);
sv.name.setText(currentStock.getName());
sv.number.setText(currentStock.getNumber());
// TODO Auto-generated method stub
return rowView;
}
protected static class ContactStockView {
protected TextView name;
protected TextView number;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
stocks.clear();
if (charText.length() == 0) {
stocks.addAll(arraylist);
} else {
for (ContactStock cs : arraylist) {
if (cs.getName().contains(charText)) {
stocks.add(cs);
}
}
}
notifyDataSetChanged();
}
}
Main class edittext code is
edittext = (EditText)findViewById(R.id.editText1);
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
//MainActivity.this.adapt.getFilter().filter(s);
String searchString=edittext.getText().toString();
adapt.filter(searchString);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
without custom adapter it is working with getfilter(). But I don't know how to filter with custom adapter. any help will be appriciated. thanks in advance