應用中有一個ListView
由於資料比較多,想用非同步載入的方法。載入之前顯示一個進度框,資料全部載入完畢之後再顯示listview。
問題描述:
這個問題不經常出現,按返回鍵結束這個activity,然後再按主介面的按鈕開啟這個activity,就這樣進進出出,四、五次的樣子,就出錯提示:The content of the adapter has changed but ListView did not receivea notification
問題程式:
Activity的 onCreate中
listview = (ListView) findViewById(R.id.listView1); listview.addFooterView(view_footer); lvAdapter = new ListViewAdapter(context); listview.setAdapter(lvAdapter); new ListTask(context).execute("");
非同步類:
class ListTask extends AsyncTask<String,Integer,String>{ ProgressDialog pd; Context context; public ListTask(Context context){ this.context=context; pd=new ProgressDialog(context); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); pd.setCancelable(false); pd.setCanceledOnTouchOutside(false); } @Override protected String doInBackground(String... params) { m_prepareList(context); //讀取資料庫中的資料到lvAdapter的dataset中 return null; } @Override protected void onPreExecute(){ pd.show(); } @Override protected void onPostExecute(String result){ lvAdapter.notifyDataSetChanged(); pd.dismiss(); } }
解決方案:
最後試了好多方法都不能解決,看了網上的一篇文章:
http://blog.csdn.net/changemyself/article/details/8116670
說是資料更新後要及時notifyDataSetChanged();
後來想了一下,我的程式中的listview.setAdapter(lvAdapter);和lvAdapter.notifyDataSetChanged();畢竟隔了一個線程。所以試著把他們靠近點。
把listview.setAdapter(lvAdapter)放到onPostExecute中lvAdapter.notifyDataSetChanged()的上面,問題結解決。