I am trying to filter the listview but getfilter method is not working,
here is the code:
@Override
public void afterTextChanged(Editable s) {
}
@Ov
Here you go. A simple baseadapter (no view recycling) that will display, and filter, a list of some custom arbitary object. In this example Object.name is the field we will use to filter.
1) In your activity, (or) where you create your ListView, enable text filtering:
class MyObject {
public String name;
}
List myData = ArrayList<>();
listview.setTextFilterEnabled(true);
2) As you already noted, in a textwatcher of an Edittext, trigger the filter on the ListAdapter:
public void onTextChanged(CharSequence s, int start, int before, int count) {
listadapter.getFilter().filter(s);
}
3) in your baseadapter, implement Filterable
. And store two copies of the data, one original, and one filtered. Be sure to access the filtered data throughout the BaseAdapter, not the unfiltered data
public class FilterableListAdapterExample extends BaseAdapter implements Filterable {
private List mData; //the original data
private List mDataFiltered;//the filtered data
private LayoutInflater mLayoutInflater;
public FilterableListAdapterExample(Context context, List data) {
mData = data;
mDataFiltered=data;
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= mLayoutInflater.inflate(R.layout.listview_item, null);
TextView textview=(TextView)convertView.findViewById(R.id.listitem_textview);
//note: we access mDataFiltered, not mData
textview.setText(mDataFiltered.get(position).name);
return convertView;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return mDataFiltered.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
//no constraint given, just return all the data. (no search)
results.count = mData.size();
results.values = mData;
} else {//do the search
List resultsData = new ArrayList<>();
String searchStr = constraint.toString().toUpperCase();
for (MyObject o : mData)
if (o.name.toUpperCase().startsWith(searchStr)) resultsData.add(o);
results.count = resultsData.size();
results.values = resultsData;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mDataFiltered = (ArrayList) results.values;
notifyDataSetChanged();
}
};
}
}