The content of the adapter has changed but ListView did not receive a notification

本文介绍了一种解决Android中ListView在使用异步加载数据时,因数据改变未及时通知刷新而导致的问题。通过调整代码逻辑,将setAdapter方法移至onPostExecute内,确保数据更新后能立即刷新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用中有一个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.youkuaiyun.com/changemyself/article/details/8116670

说是数据更新后要及时notifyDataSetChanged();

    后来想了一下,我的程序中的listview.setAdapter(lvAdapter);和lvAdapter.notifyDataSetChanged();毕竟隔了一个线程。所以试着把他们靠近点。

     把listview.setAdapter(lvAdapter)放到onPostExecute中lvAdapter.notifyDataSetChanged()的上面,问题结解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rainfall007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值