Issue
I am using a AutoCompleteTextView in my code and loading the list from database using SimpleCursorAdapter.
AutoCompleteTextView cocktailIngredientView = (AutoCompleteTextView) findViewById(R.id.item);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, mCursor,
new String[] { "field" },
new int[] { android.R.id.text1 });
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cocktailIngredientView.setAdapter(adapter);
cocktailIngredientView.setThreshold(0);
It populates the list correctly but I have two issues:
- I want this list to be sorted
- Whatever I enter, it displays the complete list. I want it to filter based on matching patterns in the list. e.g. if the list contains values Page, Tools...then if I enter T in the box, the drop-down should show only Tools. The idea is to display options which contain the entered pattern anywhere in the string text.
How can this be done?
Solution
You have to tell the adapter what items to display. I tried implementing something similar to this by using a FilterQueryProvider
that queries the database for the items that I want to display in the dropdown.
FilterQueryProvider filter = new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence constraint) {
// Make a DB query that filters based on the constraint
return //whatever query results;
}
};
myAdapter.setFilterQueryProvider(filter);
As for the situation when you select an item on the list, you have to override the CursorToStringConverter
of the SimpleCursorAdapter
. Something like:
SimpleCursorAdapter.CursorToStringConverter conv = new SimpleCursorAdapter.CursorToStringConverter() {
@Override
public CharSequence convertToString(Cursor cursor) {
int numCol = cursor.getColumnIndexOrThrow("whateverFieldYouNeed");
String term = cursor.getString(numCol);
return term;
}
};
myAdapter.setCursorToStringConverter(conv);
Answered By - Zarah
Answer Checked By - David Goodson (JavaFixing Volunteer)