java - 动态填充 AutoCompleteTextView 建议

标签 java android android-asynctask autocompletetextview

我创建了一个 AsyncTask 来在每次 AutoCompleteTextView 发生更改时从 URL 获取建议。应该可以正常工作,不知道问题出在哪里。

fragment (使用 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) {

    }
});

建议 getter :

// 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);
}

正如我在评论中所写,它实际上获取了数据,但我没有得到任何建议。

最佳答案

我有同样的任务要实现,为此我在编辑文本下方使用了一个隐藏的 ListView (我在其中输入网址或搜索词),并且 ListView 将根据使用文本观察器的编辑文本的更改从 API 填充。如果您需要其他解决方案,请尝试此操作。

关于java - 动态填充 AutoCompleteTextView 建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28852869/

相关文章:

java - 改造方法响应重用到另一个 Activity 中

java - onPostExecute() 内部的 startActivity() 不起作用

java - 强制转换通用数组的问题

安卓 : inApp purchase receipt validation google play

android - 矩阵操作矩形的 HitTest

java - 使用 AsyncTask 时出现 ExceptionInInitializerError

android - 我需要将数据从 Sqlite 数据库发送到服务器

java - 除某些字符外的所有字符串的正则表达式

java - FIX 通信模型 - 消息或套接字

java - IBM MQ 7 文件传输