ListView中notifyDataSetChanged()無法刷新數(shù)據(jù)的錯誤實例

在使用ListView需要動態(tài)刷新數(shù)據(jù)的時候,經(jīng)常會用到notifyDataSetChanged()函數(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;此時,a與b包含相同的引用,他們指向相同的對象。
但是在語句recentItems = getData()之后,List a會指向一個新的對象。而mAdapter保存的List b仍然指向原來的對象,該對象的數(shù)據(jù)也并沒有發(fā)生改變,所以Listview并不會更新。

我在頁面A中綁定了數(shù)據(jù)庫的數(shù)據(jù),在頁面B中修改了數(shù)據(jù)庫中的數(shù)據(jù),希望在返回頁面A時,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)存中的對象,而不是數(shù)據(jù)庫。所以改變數(shù)據(jù)庫中的數(shù)據(jù),并不會影響該對象。

notifyDataSetChanged()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容