The content of the adapter has changed but ListView did not receive a notification,listviewadapter
在非Ui線程中修改ListView繫結資料對象的問題
問題描述:
在非UI線程中修改了ListView繫結資料對象(如List)時,如下異常:
問題分析:
在非UI線程下不能夠對主線程中ListView綁定的List資料進行修改。
解決方案:
方法一:將對List中資料的修改放到主線程中。
方法二:將子線程中要更新的資料通過Handler傳遞到主線程中,然後在主線程中將傳遞過來的資料添加到ListView繫結資料對象List中,然後同時adapter資料改變。
在這裡主要介紹第二種方式:
具體步驟:
1.在子線程中將要更新的資料以Message的方式傳遞給主線程。
Map<String, Object>item=new HashMap<String, Object>();//擷取程式的包名String packageName=appInfo.packageName;item.put("imgIco", ico);item.put("appName", appName);item.put("packageName", packageName);Message message = new Message();message.what =SCANNING;message.obj = item;mHandler.sendMessage(message);
2.在主線程中通過Handler處理子線程發來的訊息,更新ListView的資料對象。
Handler mHandler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubswitch (msg.what) {case FLAG_LOAD_SUCCESS://完成掃描break;case SCANNING://正在掃描items.add((Map<String, Object>) msg.obj);//通知適配器資料改變adapter.notifyDataSetChanged();
listView經常出現這樣的問題,怎解決?
當你的listview中的資料發生改變時,必須通知adapter告訴它資料變了,方法是:
adapter.notifyDataSetChanged();
由於這個方法實際上是在更新UI,所以必須在UI線程也就是主線程裡進行。
android載入下一頁資料,壓力測試多次滑動報錯:The content of the adapter has changed
Adapter資料的更新必須在UI thread中來添加,並且添加完使用notify函數通知。或者貼一下源碼。