1.异常报错
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.
这个算是比较常见的ListView相关的报错了,但是如果工程很大,也很难发现出错的地方在哪儿,所以在开发的时候就要注意这方面的问题。
问题的原因是你改变了数据适配器adapter.getCount()所获取的长度,而ListView中会有一个成员变量mItemCount,mItemCount 会在ListView setAdapter,onMeasure和adapter.notifyDataSetChanged的时候重新赋值mItemCount = adapter.getCount()。在ListView layoutChildren()的时候,如果发现mItemCount != adapter.getCount(),这时候就会抛出这个异常。
解决方法:
改变adapter的数据长度和调用adapter notify方法都放在主线程中,并且是在用一个时序中。不能改变了adapter的数据长度之后再使用handler发送消息,通知adapter 调用notify。
有时候为了优化,将解析放到子线程中,此时可以新建一个list临时保存数据,然后通过handler抛到主线程中,加入adapter,然后notify。
2.adapter.notifyDataSetChanged原理
ListView中有一个成员变量mDataSetObserver,在setAdapter的时候,会将mDataSetObserver注册到adapter中,他有onChanged方法,在adapter.notifyDataSetChanged调用之后,会通知所有的mDataSetObserver,调用其onChanged,onChanged里面会调用ListView的requestLayout()方法。