Good day, I have this custom adapter with a filterable interface implemented and am getting duplicate values in the resulting list.
SearchAutoCompleteAdapter.java
public class SearchAutoCompleteAdapter extends BaseAdapter implements Filterable {
private ArrayList<BaseAutocompleteItems> resultList;
List<BaseAutocompleteItems> filteredProducts;
private LayoutInflater layoutInflater;
private Context context;
private int layout;
SearchAutoCompleteAPI searchautocomplete = new SearchAutoCompleteAPI();
public SearchAutoCompleteAdapter(Context context, int resource) {
super();
this.context = context;
this.layout = resource;
filteredProducts = new ArrayList<BaseAutocompleteItems>();
resultList = new ArrayList<BaseAutocompleteItems>();
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public Object getItem(int index) {
return resultList.get(index);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(layout, null);
}
TextView name = (TextView) convertView.findViewById(R.id.suggestion_text_id);
name.setText(resultList.get(position).getName());
return convertView;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
List<BaseAutocompleteItems> tempfilteredProducts = new ArrayList<BaseAutocompleteItems
filteredProducts.clear();
if (constraint != null || constraint.length() > 0) {
tempfilteredProducts.clear();
tempfilteredProducts = searchautocomplete.autocomplete(constraint.toString()); //webservice call
} else {
tempfilteredProducts = new ArrayList<BaseAutocompleteItems>();
}
for (BaseAutocompleteItems items : tempfilteredProducts) {
if (items.getName().contains(constraint.toString())) {
filteredProducts.add(items);
}
}
filterResults.values = filteredProducts;
filterResults.count = filteredProducts.size();
return filterResults;
}
@Override
protected void publishResults (CharSequence constraint, FilterResults results){
resultList = (ArrayList<BaseAutocompleteItems>)results.values;
if(results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
;
return filter;
}
}
If I type "yell" and press backspace for "yel" or increase my char to "yello", I get the same result and thus the ArrayList
ends up with duplicated items. I have tried clearing the lists before populating the list but nothing seems to work.
Try changing
to