I have implemented Search Filter to my SearchView in my SherlockAction Bar.
When i type m i want to show filtered results in the list view below which only starts with M and so on. But now it shows random results.
public boolean onQueryTextChange(String newText) {
Log.i("Nomad", "onQueryTextChange");
if (TextUtils.isEmpty(newText)) {
adapter.getFilter().filter("");
Log.i("Nomad", "onQueryTextChange Empty String");
placesListView.clearTextFilter();
} else {
Log.i("Nomad", "onQueryTextChange " + newText.toString());
adapter.getFilter().filter(newText.toString());
}
return true;
}
public boolean onQueryTextSubmit(String query) {
Log.i("Nomad", "onQueryTextSubmit");
return false;
}
public boolean onClose() {
Log.i("Nomad", "onClose");
return false;
}
Place this inside your adapter:
@Override
public Filter getFilter(){
return new Filter(){
@Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if (constraint != null && constraint.toString().length() > 0) {
List<String> founded = new ArrayList<String>();
for(YourListItemType item: origData){
if(item.toString().toLowerCase().contains(constraint)){
founded.add(item);
}
}
result.values = founded;
result.count = founded.size();
}else {
result.values = origData;
result.count = origData.size();
}
return result;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
clear();
for (String item : (List<String>) results.values) {
add(item);
}
notifyDataSetChanged();
}
}
}
And this inside constructor of your adapter
public MyAdapter(Context context, int layoutResourceId, String[] places) {
super(context, layoutResourceId, data);
this.context = context;
this.data = Arrays.asList(places);
this.origData = new ArrayList<String>(this.data);
}