您當前位置:
首頁 >
php開源 >
綜合技術 > ListView中notifyDataSetChanged()無法刷新數據的錯誤實例
ListView中notifyDataSetChanged()無法刷新數據的錯誤實例
來源:程序員人生 發布時間:2015-03-18 09:32:45 閱讀次數:3561次
在使用ListView需要動態刷新數據的時候,常常會用到notifyDataSetChanged()函數。
以下為兩個使用的毛病實例:
1、
沒法刷新:
private List<RecentItem> recentItems;
......
recentItems = getData()
mAdapter.notifyDataSetChanged();
正常刷新:
private List<RecentItem> recentItems;
......
recentItems.clear();
recentItems.addAll(getData);
mAdapter.notifyDataSetChanged();
緣由:
mAdapter通過構造函數獲得List a的內容,內部保存為List b;此時,a與b包括相同的援用,他們指向相同的對象。
但是在語句recentItems = getData()以后,List a會指向1個新的對象。而mAdapter保存的List
b依然指向原來的對象,該對象的數據也并沒有產生改變,所以Listview其實不會更新。
2、
我在頁面A中綁定了
數據庫的數據,在頁面B中修改了
數據庫中的數據,希望在返回頁面A時,ListView刷新顯示。
沒法刷新:
protected void onResume() {
mAdapter.notifyDataSetChanged();
super.onResume();
}
正常刷新:
protected void onResume() {
recentItems.clear();
recentItems.addAll(recentDB.getRecentList());
mAdapter.notifyDataSetChanged();
super.onResume();
}
緣由:
mAdapter內部的List指向的是內存中的對象,而不是數據庫。所以改變數據庫中的數據,其實不會影響該對象。
void
|
notifyDataSetChanged()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
|
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
------分隔線----------------------------
------分隔線----------------------------