Android AutoCompleteTextView not calling getView() method - android

This is the code I am using for custom adapter for my autocomplete textview
I tried this solution link
This solution says that item count may be 0 but in my case item count is not 0.
It never goes to getView() method. I try it calling from Fragment, I tried calling it from Activity
I tried solution from this answer as well link but it doesn't work.
It never goes inside the getView() method.
public class BusCityListAdapter extends ArrayAdapter<BusCityList> {
private ArrayList<BusCityList> cityList;
private ArrayList<BusCityList> tempCityList;
private ArrayList<BusCityList> suggestionsList;
public BusCityListAdapter(Context context, ArrayList<BusCityList> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
this.cityList = objects;
this.tempCityList = new ArrayList<BusCityList>(objects);
this.suggestionsList = new ArrayList<BusCityList>(objects);
}
#Override
public int getCount() {
System.out.println("Main List Size=="+cityList.size());
System.out.println("Temp List Size=="+tempCityList.size());
System.out.println("Suggestion List Size=="+suggestionsList.size());
return cityList.size();
}
#Override
public BusCityList getItem(int position) {
return cityList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("Inside GetView");
BusCityList busCity = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.bus_city_name_layout, parent, false);
}
MyTextView bus_name_label = (MyTextView) convertView.findViewById(R.id.bus_name_label);
if (bus_name_label != null)
bus_name_label.setText(busCity.getCity_name());
// Now assign alternate color for rows
return convertView;
}
#Override
public Filter getFilter() {
return myFilter;
}
Filter myFilter = new Filter() {
#Override
public CharSequence convertResultToString(Object resultValue) {
BusCityList busCity = (BusCityList) resultValue;
return busCity.getCity_name();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestionsList.clear();
for (BusCityList city : tempCityList) {
if (city.getCity_name().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestionsList.add(city);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestionsList;
filterResults.count = suggestionsList.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<BusCityList> c = (ArrayList<BusCityList>) results.values;
if (results != null && results.count > 0) {
clear();
for (BusCityList city : c) {
add(city);
notifyDataSetChanged();
}
}
}
};
}
Here is the code where I am setting the adapter to AutoCompleteTextView
AutoCompleteTextView txtToWhere = (AutoCompleteTextView) v.findViewById(R.id.txtToWhere);
busCityListAdapter = new BusCityListAdapter(getActivity(), arrayList);
txtToWhere.setAdapter(busCityListAdapter);
busCityListAdapter.notifyDataSetChanged();

Related

Filter ListView from custom base adapter

I am trying to implement the search in the Custom ListView. I am able to search in my list. But the problem with my adapter is once the query string is not available in the list even if i backspace my string and write the correct string it's not able to search it. And my other question is how can I refresh the list with my old list which was present before the search.
Here is my code:
public class ChartListAdapter extends BaseAdapter implements Filterable {
ArrayList<ChartModel> list;
Context context;
public ChartListAdapter(ArrayList<ChartModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
if(list != null) {
return list.size();
} else {
return 0;
}
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null) {
view = View.inflate(context, R.layout.chart_card, null);
}
TextView chart_name = view.findViewById(R.id.chart_name);
SwitchCompat switchCompat = view.findViewById(R.id.chart_selected);
switchCompat.setTag(list.get(i).getChart_id());
chart_name.setText(list.get(i).getChart_name());
switchCompat.setChecked(list.get(i).getCard_selected());
switchCompat.setOnCheckedChangeListener((compoundButton, b) -> {
String getTag = compoundButton.getTag().toString();
Toast.makeText(context, getTag + " is selected :" + b, Toast.LENGTH_LONG).show();
});
return view;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint == null || constraint.length() == 0){
filterResults.count = list.size();
filterResults.values = list;
}else{
ArrayList<ChartModel> resultsModel = new ArrayList<>();
String searchStr = constraint.toString().toLowerCase();
for(ChartModel itemsModel:list){
if(itemsModel.getChart_id().contains(searchStr)){
resultsModel.add(itemsModel);
}
filterResults.count = resultsModel.size();
filterResults.values = resultsModel;
}
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
list = (ArrayList<ChartModel>) results.values;
notifyDataSetChanged();
}
};
}
}
Any suggestion will be of great help. Thank you for your time.
Change your adapter class like this
public class ChartListAdapter extends BaseAdapter implements Filterable {
ArrayList<ChartModel> list;
ArrayList<ChartModel> filteredList;
Context context;
public ChartListAdapter(ArrayList<ChartModel> list, Context context) {
this.list = list;
this.filteredList = list;
this.context = context;
}
#Override
public int getCount() {
if(filteredList != null) {
return filteredList.size();
} else {
return 0;
}
}
#Override
public Object getItem(int i) {
return filteredList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null) {
view = View.inflate(context, R.layout.chart_card, null);
}
TextView chart_name = view.findViewById(R.id.chart_name);
SwitchCompat switchCompat = view.findViewById(R.id.chart_selected);
switchCompat.setTag(filteredList.get(i).getChart_id());
chart_name.setText(filteredList.get(i).getChart_name());
switchCompat.setChecked(filteredList.get(i).getCard_selected());
switchCompat.setOnCheckedChangeListener((compoundButton, b) -> {
String getTag = compoundButton.getTag().toString();
Toast.makeText(context, getTag + " is selected :" + b, Toast.LENGTH_LONG).show();
});
return view;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint == null || constraint.length() == 0){
filteredList = list;
}else{
ArrayList<ChartModel> resultsModel = new ArrayList<>();
String searchStr = constraint.toString().toLowerCase();
for(ChartModel itemsModel:list){
if(itemsModel.getChart_id().contains(searchStr)){
resultsModel.add(itemsModel);
}
filteredList = resultsModel;
}
}
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (ArrayList<ChartModel>) results.values;
notifyDataSetChanged();
}
};
}
}

autocomplete textview updating the list for it through another api not googleapi

I am having trouble with Autocomplete Textview where I am calling the list for it through an API
this is the code that I am using for Adapter of the list
class PickDropLocationAdapter extends ArrayAdapter {
ArrayList PickDropBeans, temppickDropBean, suggestions;
public PickDropLocationAdapter(Context context, ArrayList<PickDropBean> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
this.PickDropBeans = objects;
this.temppickDropBean = new ArrayList<PickDropBean>(objects);
this.suggestions = new ArrayList<PickDropBean>(objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PickDropBean PickDropBean = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_pick_drop, parent, false);
}
TextView txtpickDropBean = (TextView) convertView.findViewById(R.id.tvCustomer);
ImageView ivpickDropBeanImage = (ImageView) convertView.findViewById(R.id.ivCustomerImage);
if (txtpickDropBean != null)
txtpickDropBean.setText(PickDropBean.getLocationname() );
/*if (ivpickDropBeanImage != null && PickDropBean.getProfilePic() != -1)
ivpickDropBeanImage.setImageResource(PickDropBean.getProfilePic());*/
// Now assign alternate color for rows
// if (position % 2 == 0)
// convertView.setBackgroundColor(getContext().getColor(R.color.odd));
// else
// convertView.setBackgroundColor(getContext().getColor(R.color.even));
return convertView;
}
#Override
public Filter getFilter() {
return myFilter;
}
Filter myFilter = new Filter() {
#Override
public CharSequence convertResultToString(Object resultValue) {
PickDropBean PickDropBean = (PickDropBean) resultValue;
return PickDropBean.getLocationname() ;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();
for (PickDropBean people : temppickDropBean) {
if (people.getLocationname().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestions.add(people);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<PickDropBean> c = (ArrayList<PickDropBean>) results.values;
if (results != null && results.count > 0) {
clear();
for (PickDropBean cust : c) {
add(cust);
notifyDataSetChanged();
}
}
}
};
}
And the Volley is used for calling the API within which I am parsing my JSON object through API and then setting the list and the adapter
error is
ava.lang.NullPointerException: collection == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)

Android autocomplete text view doesn't show suggestions

what is wrong with my code? i am getting the entire list as suggestion in autocomplete text view.
public class ContactAdapter extends ArrayAdapter<String> {
List<ContactList> contactLists;
List<ContactList> suggestions;
LayoutInflater inflater;
public ContactAdapter(Activity context, int id, ArrayList list) {
super(context, id,list);
this.contactLists = list;
suggestions = new ArrayList<>();
inflater = (LayoutInflater.from(context));
}
private View getCustomView(final int position, View view, ViewGroup viewGroup){
view = inflater.inflate(R.layout.custom_contact_layout, null);
TextView name = (TextView)view.findViewById(R.id.textView);
TextView email = (TextView)view.findViewById(R.id.textView2);
name.setText(contactLists.get(position).getName());
email.setText(contactLists.get(position).getEmail());
return view;
}
#Override
public View getView(int position , View view , ViewGroup parent)
{
return getCustomView(position,view,parent);
}
#Override
public Filter getFilter() {
Filter nameFilter = new Filter() {
#Override
public CharSequence convertResultToString(Object result) {
return ((ContactList) result).getName();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
suggestions.clear();
for (int contactName = 0; contactName < contactLists.size(); contactName++) {
if (contactLists.get(contactName).getName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestions.add(contactLists.get(contactName));
Log.d(">add>", contactLists.get(contactName).getName() + "");
}
}
filterResults.values = suggestions;
filterResults.count = suggestions.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
suggestions.clear();
suggestions = (List<ContactList>) results.values;
notifyDataSetChanged();
} else
notifyDataSetInvalidated();
}
};
return nameFilter;
}
}
Tell me how can i get only the filtered results as suggestions.In perform filter method only the filtered results get added. Why it is not getting reflected in publishResults method?
Change your code to:
Log.d(">>","called");
if(results.count >0){
suggestions.clear();
suggestions = (List<ContactList>) results.values;
notifyDataSetChanged();
}
else
notifyDataSetInvalidated();
}

Android AutoComplete with custom filter having duplicate results

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.
Nothing wrong with the code in the question. just a checklist for anyone first. make sure you call Clear() on the ArrayList being returned in the line.
tempfilteredProducts = searchautocomplete.autocomplete(constraint.toString()); //webservice call
from the API call first before populating the values from the webservice and sending it back to tempfilteredProducts(i.e before every api request). That way you avoid duplicate values from the autocompletetextview string as in my case in the question.
Try changing
if (items.getName().contains(constraint.toString()))
to
if (items.getName().startsWith(constraint.toString()))

Android AutoCompleteTextView with Custom Adapter filtering not working

I've the Custom CustomerAdapter
public class CustomerAdapter extends ArrayAdapter<Customer> {
private final String MY_DEBUG_TAG = "CustomerAdapter";
private ArrayList<Customer> items;
private int viewResourceId;
public CustomerAdapter(Context context, int viewResourceId, ArrayList<Customer> items) {
super(context, viewResourceId, items);
this.items = items;
this.viewResourceId = viewResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
Customer customer = items.get(position);
if (customer != null) {
TextView customerNameLabel = (TextView) v.findViewById(R.id.customerNameLabel);
if (customerNameLabel != null) {
customerNameLabel.setText(String.valueOf(customer.getName()));
}
}
return v;
}
}
and customer_auto layout
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/customerNameLabel"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:padding="10dp" android:textSize="16sp"
android:textColor="#000">
</TextView>
and on my public void onCreate
AutoCompleteTextView customerAutoComplete = (AutoCompleteTextView) findViewById(R.id.autocomplete_customer);
CustomerAdapter customerAdapter = new CustomerAdapter(this, R.layout.customer_auto, customerList);
customerAutoComplete.setAdapter(customerAdapter);
and Customer.java
public class Customer implements Parcelable {
private int id;
private String name = "";
public Customer() {
// TODO Auto-generated constructor stub
}
/**
* This will be used only by the MyCreator
*
* #param source
*/
public Customer(Parcel source) {
/*
* Reconstruct from the Parcel
*/
id = source.readInt();
name = source.readString();
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
#Override
public Customer createFromParcel(Parcel source) {
return new Customer(source);
}
#Override
public Customer[] newArray(int size) {
return new Customer[size];
// TODO Auto-generated method stub
}
};
#Override
public String toString() {
return this.name;
}
}
But the auto suggest box does not filter correctly. for eg; if i type an in the test box customers starting with br are showing up!
I have to over-ride the getFilter() method of the Adapter
Here is the code which worked for me, thanks to sacoskun
public class CustomerAdapter extends ArrayAdapter<Customer> {
private final String MY_DEBUG_TAG = "CustomerAdapter";
private ArrayList<Customer> items;
private ArrayList<Customer> itemsAll;
private ArrayList<Customer> suggestions;
private int viewResourceId;
public CustomerAdapter(Context context, int viewResourceId, ArrayList<Customer> items) {
super(context, viewResourceId, items);
this.items = items;
this.itemsAll = (ArrayList<Customer>) items.clone();
this.suggestions = new ArrayList<Customer>();
this.viewResourceId = viewResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
Customer customer = items.get(position);
if (customer != null) {
TextView customerNameLabel = (TextView) v.findViewById(R.id.customerNameLabel);
if (customerNameLabel != null) {
// Log.i(MY_DEBUG_TAG, "getView Customer Name:"+customer.getName());
customerNameLabel.setText(customer.getName());
}
}
return v;
}
#Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = ((Customer)(resultValue)).getName();
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null) {
suggestions.clear();
for (Customer customer : itemsAll) {
if(customer.getName().toLowerCase().startsWith(constraint.toString().toLowerCase())){
suggestions.add(customer);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Customer> filteredList = (ArrayList<Customer>) results.values;
if(results != null && results.count > 0) {
clear();
for (Customer c : filteredList) {
add(c);
}
notifyDataSetChanged();
}
}
};
}
This is my solution. I feel like it's a bit cleaner (doesn't use 3 separate, confusing ArrayLists) than the accepted one, and has more options. It should work even if the user types backspace, because it doesn't remove the original entries from mCustomers (unlike the accepted answer):
public class CustomerAdapter extends ArrayAdapter<Customer> {
private LayoutInflater layoutInflater;
List<Customer> mCustomers;
private Filter mFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
return ((Customer)resultValue).getName();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null) {
ArrayList<Customer> suggestions = new ArrayList<Customer>();
for (Customer customer : mCustomers) {
// Note: change the "contains" to "startsWith" if you only want starting matches
if (customer.getName().toLowerCase().contains(constraint.toString().toLowerCase())) {
suggestions.add(customer);
}
}
results.values = suggestions;
results.count = suggestions.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
clear();
if (results != null && results.count > 0) {
// we have filtered results
addAll((ArrayList<Customer>) results.values);
} else {
// no filter, add entire original list back in
addAll(mCustomers);
}
notifyDataSetChanged();
}
};
public CustomerAdapter(Context context, int textViewResourceId, List<Customer> customers) {
super(context, textViewResourceId, customers);
// copy all the customers into a master list
mCustomers = new ArrayList<Customer>(customers.size());
mCustomers.addAll(customers);
layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = layoutInflater.inflate(R.layout.customerNameLabel, null);
}
Customer customer = getItem(position);
TextView name = (TextView) view.findViewById(R.id.customerNameLabel);
name.setText(customer.getName());
return view;
}
#Override
public Filter getFilter() {
return mFilter;
}
}
Instead of overriding getFilter() method in adapter, simply we can override the toString() of the userDefined object (Customer).
In toString() just return the field based on what you need to filter. It worked for me.
In my example I'm filtering based on names:
public class Customer{
private int id;
private String name;
#Override
public String toString() {
return this.name;
}
}
In the above code publisHResults() method gives the concurrent modification exception....
we have to modify the code as:
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Customer> filteredList = (ArrayList<Customer>) results.values;
ArrayList<Customer> customerList=new ArrayList<Customer>();
if (results != null && results.count > 0) {
clear();
for (Customer c : filteredList) {
customerList.add(c);
}
Iterator<Customer> customerIterator=getResult.iterator();
while (customerIterator.hasNext()) {
Customer customerIterator=customerIterator.next();
add(customerIterator);
}
notifyDataSetChanged();
}
}
Maybe this is too late, you dont need to override all of these functions , the only function to override is :
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
Customer customer = getItem(position);
if (customer != null) {
TextView customerNameLabel = (TextView) v.findViewById(R.id.customerNameLabel);
if (customerNameLabel != null) {
customerNameLabel.setText(String.valueOf(customer.getName()));
}
}
return v;
}
consider I change :
Customer customer = items.get(position);
Customer customer = getItem(position);
pay attention, you should not declare new ListItems,
private ArrayList<Customer> items;
because ArrayAdapter works with its own mObjects, and filter this list not your items list,
So you should use getItem function to access items.
then there is no reason to write your ArrayFilter.
I don't know where you retrieving the getResult. I think the solution in this case for don't have the concurrent modification is:
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Customer> filteredList = (ArrayList<Customer>) results.values;
ArrayList<Customer> customerList=new ArrayList<Customer>();
if (results != null && results.count > 0) {
clear();
try{
for (Customer c : filteredList) {
customerList.add(c);
}
}catch(Exception e){
Log.e("PEEEETAAAAAAAA", "AutoCompletaError: "+e.getMessage()+" "+e.getCause()+" "+e.getLocalizedMessage());
}
Iterator<Customer> customerIterator=customerList.iterator();
while (customerIterator.hasNext()) {
Customer customerIterator=customerIterator.next();
add(customerIterator);
}
notifyDataSetChanged();
}
}
I hope that this post will help people with implementation of a similar custom functionality in the future. I based this on my version of adapter used for displaying tag suggestions in my microblogging app:
public class TagSuggestionsAdapter extends ArrayAdapter<String> implements Filterable
Extending ArrayAdapter to have less boilerplate code. Implementing Filterable to change filter behavior later.
private List<String> allTags;
private List<String> tagSuggestions;
private Context context;
public TagSuggestionsAdapter(List<String> initialTagSuggestions, List<String> allTags,
Context context) {
super(context, R.layout.item_tag_suggestion, initialTagSuggestions);
this.tagSuggestions = initialTagSuggestions;
this.allTags = allTags;
this.context = context;
}
Basically in constructor you need to pass a list that will be displayed initially - it'll later become a list with filtered results (this is also a reference to a list that will be taken into consideration when calling notifyDataSetChanged()) and obviously a list on which you can base your filtering (allTags in my case). I'm also passing Context for layout inflation in getView().
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.item_tag_suggestion, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tagSuggestionTextView.setText(tagSuggestions.get(position));
return convertView;
}
static class ViewHolder {
#BindView(R.id.tag_suggestion_text_view)
TextView tagSuggestionTextView;
ViewHolder(View itemView) {
ButterKnife.bind(this, itemView);
}
}
Above you can see a simple view holder pattern with a little help from Butterknife to inflate a custom row layout.
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
List<String> filteredTags = filterTagSuggestions(constraint.toString(), allTags);
FilterResults filterResults = new FilterResults();
filterResults.values = filteredTags;
filterResults.count = filteredTags.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
tagSuggestions.clear();
if (results != null && results.count > 0) {
List<?> filteredTags = (List<?>) results.values;
for (Object filteredTag : filteredTags) {
if (filteredTag instanceof String) {
tagSuggestions.add((String) filteredTag);
}
}
}
notifyDataSetChanged();
}
};
}
This is the least boilerplate code I could write. Your only concern is method filterTagSuggestions that should return a filtered list of tags based on input from user (CharSequence constraint). Hope that summarized and organized necessary info a little bit.
If you get ConcurrentModificationException exception.
Replace ArrayList with the thread safe CopyOnWriteArrayList.
Here you can find detatils answer
I have non-update and modify orginal list issues from above answer. I fixed this problem with this codes.
public class AdapterAutoCompleteTextView extends ArrayAdapter<ItemWord> {
private int LayoutID;
private int TextViewID;
private LayoutInflater Inflater;
private List<ItemWord> ObjectsList;
public AdapterAutoCompleteTextView(Context ActivityContext, int ResourceID, int TextViewResourceID, List<ItemWord> WordList) {
super(ActivityContext, ResourceID, TextViewResourceID, new ArrayList<ItemWord>());
LayoutID = ResourceID;
TextViewID = TextViewResourceID;
ObjectsList = WordList;
Inflater = LayoutInflater.from(ActivityContext);
}
#Override
public View getView(int Position, View ConvertView, ViewGroup Parent) {
ItemWord Word = getItem(Position);
if(ConvertView == null) {
ConvertView = Inflater.inflate(LayoutID, null);
ResultHolder Holder = new ResultHolder();
Holder.ResultLabel= (TextView) ConvertView.findViewById(TextViewID);
ConvertView.setTag(Holder);
}
ResultHolder Holder = (ResultHolder) ConvertView.getTag();
Holder.ResultLabel.setText(Word.getSpelling());
return ConvertView;
}
#Override
public Filter getFilter() {
return CustomFilter;
}
private Filter CustomFilter = new Filter() {
#Override
public CharSequence convertResultToString(Object ResultValue) {
return ((ItemWord) ResultValue).getSpelling();
}
#Override
protected FilterResults performFiltering(CharSequence Constraint) {
FilterResults ResultsFilter = new FilterResults();
ArrayList<ItemWord> OriginalValues = new ArrayList<ItemWord>(ObjectsList);
if(Constraint == null || Constraint.length() == 0){
ResultsFilter.values = OriginalValues;
ResultsFilter.count = OriginalValues.size();
} else {
String PrefixString = Constraint.toString().toLowerCase();
final ArrayList<ItemWord> NewValues = new ArrayList<ItemWord>();
for(ItemWord Word : OriginalValues){
String ValueText = Word.getSpelling().toLowerCase();
if(ValueText.startsWith(PrefixString))
NewValues.add(Word);
}
ResultsFilter.values = NewValues;
ResultsFilter.count = NewValues.size();
}
return ResultsFilter;
}
#Override
protected void publishResults(CharSequence Constraint, FilterResults Results) {
clear();
if(Results.count > 0)
addAll(((ArrayList<ItemWord>) Results.values));
else
notifyDataSetInvalidated();
}
};
private static class ResultHolder {
TextView ResultLabel;
}
}
This is most important line for non-update and modify orginal list issue:
super(ActivityContext, ResourceID, TextViewResourceID, new ArrayList<ItemWord>());
Particularly those
super(ActivityContext, ResourceID, TextViewResourceID, new ArrayList());
I hope this solution will be help you :)

Categories

Resources