在使用ListView需要?jiǎng)討B(tài)刷新數(shù)據(jù)的時(shí)候,經(jīng)常會(huì)用到notifyDataSetChanged()函數(shù)。
以下為兩個(gè)使用的錯(cuò)誤實(shí)例:
1、
無法刷新:
private List<RecentItem> recentItems;
......
recentItems = getData()
mAdapter.notifyDataSetChanged();
正常刷新:
private List<RecentItem> recentItems;
......
recentItems.clear();
recentItems.addAll(getData);
mAdapter.notifyDataSetChanged();
原因:
mAdapter通過構(gòu)造函數(shù)獲取List a的內(nèi)容,內(nèi)部保存為List b;此時(shí),a與b包含相同的引用,他們指向相同的對(duì)象。
但是在語句recentItems = getData()之后,List a會(huì)指向一個(gè)新的對(duì)象。而mAdapter保存的List b仍然指向原來的對(duì)象,該對(duì)象的數(shù)據(jù)也并沒有發(fā)生改變,所以Listview并不會(huì)更新。
2、
我在頁面A中綁定了數(shù)據(jù)庫的數(shù)據(jù),在頁面B中修改了數(shù)據(jù)庫中的數(shù)據(jù),希望在返回頁面A時(shí),ListView刷新顯示。
無法刷新:
protected void onResume() {
mAdapter.notifyDataSetChanged();
super.onResume();
}
正常刷新:
protected void onResume() {
recentItems.clear();
recentItems.addAll(recentDB.getRecentList());
mAdapter.notifyDataSetChanged();
super.onResume();
}
原因:
mAdapter內(nèi)部的List指向的是內(nèi)存中的對(duì)象,而不是數(shù)據(jù)庫。所以改變數(shù)據(jù)庫中的數(shù)據(jù),并不會(huì)影響該對(duì)象。
void notifyDataSetChanged()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.