动态更新 AutoCompleteTextView 适配器

问题描述:

我想通过从 RESTful Web 服务获取列表来定期更改 AutoCompleteTextview 给出的建议,但无法顺利运行.我设置了一个硬编码的建议列表以确保它有效:

I want to periodically change the suggestions given by an AutoCompleteTextview by getting the list from a RESTful web service, and can't get it working smoothly. I set up a hard-coded list of suggestions to make sure it's working:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, new String[] {"Hi", "Ho"});
speciesName.setAdapter(adapter);//my autocomplete tv

我在 textview 上有一个 TextWatcher,当文本更改时会启动非阻塞调用以获取新的建议列表——这部分获取新列表的工作正常.然后我想重置适配器,如下所示:

I have got a TextWatcher on the textview and when the text changes that launches a non-blocking call to get a new list of suggestions -- this part which gets a new list is working fine. Then I want to reset the adapter, like so:

public void setOptionsAndUpdate(String[] options) {
    Log.d(TAG, "setting options");
    //speciesName.setAdapter((ArrayAdapter<String>)null);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, options);
    speciesName.setAdapter(adapter);
}

此方法被调用,但不起作用——尽管调用了 setAdapter,但建议列表要么消失,要么显示的建议保持不变.

This method is called, but doesn't work -- the list of suggestions either disappears or the displayed suggestions remain unchanged despite the call to setAdapter.

这甚至是正确的方法吗?我查看了 SimpleCursorAdapter,但看不到如何将我的 Web 服务注册为内容提供者.(它的形式是 http://www.blah.com/query?term=XX,其中 XX 是来自我的应用程序的输入,而响应是一个 JSON 字符串数组.)

Is this even the right approach? I looked at SimpleCursorAdapter but couldn't see how to register my web service as a content provider. (It's of the form http://www.blah.com/query?term=XX, where the XX is the input from my app, and the response is a JSON Array of strings.)

这是我更新 AutoCompleteTextView 的方式:

This is how I update my AutoCompleteTextView:

String[] data = terms.toArray(new String[terms.size()]);  // terms is a List<String>
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(activity, android.R.layout.simple_dropdown_item_1line, data);
keywordField.setAdapter(adapter);  // keywordField is a AutoCompleteTextView
if(terms.size() < 40) keywordField.setThreshold(1); 
else keywordField.setThreshold(2);

当然,这是静态的,不处理无线建议,但我也可以建议您在将更改分配给 AutoCompleteTextView 后通知适配器:

Now of course, this is static and doesn't deal with an over-the-air suggestions but, I can also suggest you to notify adapter for the changes after you assign it to the AutoCompleteTextView:

adapter.notifyDataSetChanged();   

希望这会有所帮助.

-serkan