【发布时间】:2014-12-13 12:21:09
【问题描述】:
我在后台创建 ListView 的内容,并在添加每个项目时更新 ListView 适配器。通常它可以正常工作,但有时我会收到此错误。奇怪的是,它在我的 Galaxy s4 mini 中发生的频率是我的 HTC Sensation 的 10 倍。我不明白为什么会发生这种情况,因为我通过 UI 线程清楚地通知了适配器。有什么想法吗?
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(2131100779, class
util.TouchInterceptor) with Adapter(class com.bill.deuterh.ListActivity$ListAdapter)]
异步任务:
private class AsyncCaller extends AsyncTask<Void,Void,Void>{
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
ListActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
findViewById(R.id.progress_bar).setVisibility(View.GONE);
}
});
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for (int i=0;i<table.length;i++){
if(isCancelled()){break;}
myList.add(createObject(table[i])));
ListActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
ListAdapter.notifyDataSetChanged();
}
});
}
return null;
}
}
(如果重要,我将 Listview 转换为 TouchInterceptor,这是一个修改后的 google 类,用于支持通过拖放重新排列 listview 项。)
【问题讨论】:
-
为什么不将
Listadapter.notifyDataSetChanged()放入onProgressUpdate()并通过publishProgress调用更新。各位,asynctask 自带 UI 运行方法!使用它们。AsyncTask很强大,但不是你使用它的方式 -
在 OnPostExecute 中设置 ListView 适配器。
标签: android android-listview android-asynctask android-adapter