【发布时间】:2015-03-04 19:23:07
【问题描述】:
我创建了一个AsyncTask 来在每次AutoCompleteTextView 发生更改时从 URL 获取建议。它应该可以正常工作,我不知道问题是什么。
片段(带有 AutoCompleteTextView):
atv = (AutoCompleteTextView) view.findViewById(R.id.atvMovieName);
// adding event listeners for text on the auto complete text view
atv.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
SuggestionFetcher fetcher = new SuggestionFetcher(getActivity(), atv);
String title = s.toString().replace(" ", "%20");
try {
URL url = new URL("http://imdbapi.com/?s=" + title + "&r=xml");
fetcher.execute(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
SuggestionFetcher:
// suggestion titles will be saved here
private Stack<String> suggestions;
// this is the auto complete text view we will be handling
private AutoCompleteTextView atv;
// and it's adapter
private ArrayAdapter<String> adapter;
// context of the activity or fragment
private Context context;
private static final String TAG = "Suggestion Fetcher";
public SuggestionFetcher(Context c, AutoCompleteTextView atv) {
this.atv = atv;
this.context = c;
this.suggestions = new Stack<String>();
}
@Override
protected Stack<String> doInBackground(URL... params) {
// get the data...
this.suggestions.add(title);
return this.suggestions;
}
@Override
protected void onPostExecute(Stack<String> strings) {
super.onPostExecute(strings);
Log.v(TAG, "finished with the data: " + strings); // works, shows the results I wanted
// update the list view
this.adapter = new ArrayAdapter<String>(this.context, android.R.layout.simple_list_item_1, strings);
this.atv.setAdapter(this.adapter);
}
正如我在 cmets 中所写,它实际上获取了数据,但我没有得到任何建议。
【问题讨论】:
-
只要按照我的回答:stackoverflow.com/a/19860624/2252830
标签: java android android-asynctask autocompletetextview