我从网站解析一些xml内容。解析新闻项目时,我想在列表中显示他。当我解析每个项目时,我称之为onNewItemLoaded
方法,需要更新列表视图。我知道适配器需要在UI线程中更新,所以我在runOnUiThread
中启动它。但我仍然得到一个错误。我做错了什么?
private ListView listView;
private NewsAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView);
final Parser parser = new Parser();
adapter = new NewsAdapter(this,parser.getNews());
listView.setAdapter(adapter);
parser.setParserClient(new Parser.ParserClient() {
@Override
public void onNewItemLoaded(Item item) {
// Update in UI Thread! What's wrong?!
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.updateList(parser.getNews());
adapter.notifyDataSetChanged();
}
});
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
parser.fetchXML("www.example.org"); // run separate thread
}
});
}
来自LogCat:
java.lang.IllegalStateException: The content of the adapter has changed but
ListView did not receive a notification. Make sure the content of your adapter
is not modified from a background thread, but only from the UI thread.
Make sure your adapter calls notifyDataSetChanged() when its content changes.
[in ListView(2130968576, class android.widget.ListView) with Adapter(class com.example.censor_client.NewsAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1555)
at android.widget.AbsListView.onLayout(AbsListView.java:2087)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14817)