Autocomplete Text View + Json Server to get Tags Dynamically
I am developing an android application. I have an autocompleteTextView in my layout. I want to populate this textView with the suggestions from my server. There are around 400 keywords on the server and they will increase in near future so i can not parse all the tags at once and then check for suggestions. The autocompleteTextView should work more like as the google search, so that i parse only when the user typed in something and that parsing happens on UI thread.
But i am here not able to trigger that parser since i am not able to get that callback method or may be the event which senses that user has typed something or may be edited some text.
setOnEditorActionListen开发者_JS百科er works only when the user presses the enter button on the soft keyboard.
Thanks in advance
You can use the Filter interface to implement this as well. Turns out Filter.performFiltering() is called off the UI thread just for this type of purpose. Here is some code I use to do this:
Filter filter = new Filter() {
@Override
public CharSequence convertResultToString(Object resultValue) {
return resultValue.toString();
}
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
if( charSequence == null ) return null;
try {
// This call hits the server with the name I'm looking for and parses the JSON returned for the first 25 results
PagedResult results = searchByName( charSequence.toString(), 1, 25, true);
FilterResults filterResults = new FilterResults();
filterResults.values = results.getResults();
filterResults.count = results.getResults().size();
return filterResults;
} catch (JSONException e) {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if( filterResults != null ) {
adapter.clear();
adapter.addAll( (List<MyObject>)filterResults.values );
}
}
};
Then using the Filter:
private AutoCompleteTextView beverageName;
...
beverageName = findViewById( R.id.beverageName );
ListAdapter adapter = ...
adapter.setFilter(filter);
beverageName.setAdapter(adapter);
You can use the TextWatcher interface to do something whenever the user changes the text in an EditText view. Just implement one or more of TextWatcher's methods, I usually use onTextChanged()
. Hope that helps!
精彩评论