I have problem with my AutoCompleteTextView,
When I choose one of the suggestion,
It should show the Product Name (Junk Food or Western Food). Anyone please help me to solve this. Below is Adapter & Filter Class.
Filter Class public class ProductFilter extends Filter { AdapterProductAutoComplete adapterProductAutoComplete; List originalList; List filteredList;
public ProductFilter (AdapterProductAutoComplete adapterProductAutoComplete, List<Product>
originalList){
super();
this.adapterProductAutoComplete = adapterProductAutoComplete;
this.originalList = originalList;
this.filteredList = new ArrayList<>();
}
@Override
protected Filter.FilterResults performFiltering (CharSequence constraint){
filteredList.clear();
final FilterResults results = new FilterResults();
if(constraint == null || constraint.length() == 0){
filteredList.addAll(originalList);
}else{
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Product product : originalList){
if(product.getProductName().toLowerCase().contains(filterPattern) || Integer
.toString(product.getProductId()).toLowerCase().contains(filterPattern)){
filteredList.add(product);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapterProductAutoComplete.filteredProducts.clear();
adapterProductAutoComplete.filteredProducts.addAll((List) results.values);
adapterProductAutoComplete.notifyDataSetChanged();
}
}
Adapter Class
public class AdapterProductAutoComplete extends ArrayAdapter<Product>{
private final List<Product> products;
public List<Product> filteredProducts = new ArrayList<>();
public AdapterProductAutoComplete(Context context, List<Product> products){
super(context, 0, products);
this.products = products;
}
@Override
public int getCount(){
return filteredProducts.size();
}
@Override
public Filter getFilter(){
return new ProductFilter(this, products);
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
Product product = filteredProducts.get(position);
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_row_actproduct, parent, false);
TextView tvCode = (TextView) convertView.findViewById(R.id.actproduct_productcode);
TextView tvName = (TextView) convertView.findViewById(R.id.actproduct_productname);
tvCode.setText(Integer.toString(product.getProductId()));
tvName.setText(product.getProductName());
return convertView;
}
}
Override toString()
method in your Product
class because AutoCompleteTextView
takes value from toString()
. Add this code to your Product
class:-
@Override
public String toString(){
return getProductName();
}
The default implementation of toString() method in Object class is this:-
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
it is what you are getting now.