情况
写安卓,跑代码。程序异常终止,抛出错误。
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中去找,不然你会发现根本没有这个函数。
解决
之前:
之后:
完美解决。