AutoCompleteTextView with SimpleAdapter

While I was messing with AutoCompleteTextView, I wanted to specify my own Adapter for it.
I have created a custom adapter which extends SimpleAdapter and implements Filterable for filtering capabilities.

There were no problems till showing the filtered results to the user. I could not be able display the filtered results on the UI as a drop down list attached to the auto complete text. Then I needed to decompile the source code of AutoCompleteTextView.class and learnt how it works.

Here is my example;


public class CountrySimpleAdapter extends SimpleAdapter implements Filterable {

private ArrayList‹HashMap‹String, String›› mAllData, mDataShown;

public CountrySimpleAdapter(Context context, List data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
mDataShown = (ArrayList‹HashMap‹String, String››) data;
mAllData = (ArrayList‹HashMap‹String, String››) mDataShown.clone();
}

@Override
public Filter getFilter() {
Filter nameFilter = new Filter(){

@Override
public String convertResultToString(Object resultValue) {
return ((HashMap‹String, String›)(resultValue)).get(Country.NAME);
}

@Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null)
{
ArrayList‹HashMap‹String, String›› tmpAllData = mAllData;
ArrayList‹HashMap‹String, String›› tmpDataShown = mDataShown;
tmpDataShown.clear();
for(int i = 0; i ‹ tmpAllData.size(); i++)
{
if(tmpAllData.get(i).get(Country.NAME).toLowerCase().startsWith(constraint.toString().toLowerCase()))
{
tmpDataShown.add(tmpAllData.get(i));
}
}

FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
}
else
{
return new FilterResults();
}
}

@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if(results != null && results.count › 0)
{
notifyDataSetChanged();
}
}};

return nameFilter;
}
}


I hope that there is going to be a better way to achieve this task in the upcoming SDKs.

Comments

Anonymous said…
test
Kira W said…
I enjoyedd reading your post

Popular posts from this blog

Configure hosts File in Android

Is Wharton Business Foundations Specialization Good?

iTunes cannot restore the iPhone because Find My iPhone is on and applications are gone!