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);
}
Get the filter from the adapter and filter vy the string changed in the seachview field on query changed.
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
getListAdapter().getFilter().filter(newText);
return true;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With