我在後臺創建一個ListView的內容,並且當添加每個項目時,我更新ListView適配器。通常它工作正常,但有時候我得到此錯誤。奇怪的是,它在我的Galaxy S4迷你版中發生的次數要比我的HTC Sensation多出10倍。我不明白爲什麼會發生這種情況,因爲我明確通過UI線程通知適配器。有什麼想法嗎 ?Android - 在AsyncTask中創建ListView內容導致隨機崩潰
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)]
的AsyncTask:
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;
}
}
(如果它的事項,我投列表視圖作爲TouchInterceptor其是用於支持與拖放列表視圖項的重排的改性谷歌類。)
爲什麼不把'Listadapter.notifyDataSetChanged()'放到'onProgressUpdate()'中並通過'publishProgress'調用更新。人們,asynctask帶有UI運行方法!使用它們。 'AsyncTask'功能強大,但不是以這種方式使用它 – Mike 2014-12-13 12:30:38
在OnPostExecute中設置ListView適配器。 – 2014-12-13 12:30:43