java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive

情况

写安卓,跑代码。程序异常终止,抛出错误。

java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131558546, class android.widget.ListView) with Adapter(class com.example.lohiaufung.lab5.GoodAdapterForShoppingCar)]

大概意思是说,改变了adapter但是没有调用notifyDataSetChanger()方法。


分析

参考:https://stackoverflow.com/questions/3669325/notifydatasetchanged-example

查了下,在stackoverflow查到了原因,

For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.

When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.

翻译过来就是说:

对于一个ArrayAdapter, notifyDataSetChanged() 只有在你使用了Adapter的add(), insert(), remove(), clear(), 之后才起作用。
当一个ArrayAdapter被创建的时候,它持有了你传入的List的引用。如果你传入的List是一个Activity的成员,然后改变了这个作为Activity成员的List, ArrayAdapter仍然持有的是这个List的引用。但是,Adapter并不知道这个List在Activity中被改变了。

所以,我们在改变List之后,调用一下notifyDataSetChanged()就好了。
这里要注意!这个是ArrayAdapter的方法,不然到List中去找,不然你会发现根本没有这个函数。


解决

之前:
这里写图片描述
之后:
这里写图片描述
完美解决。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值