第一部分 crash描述及原因分析
在ListView和Adapter搭配使用时,有一个经典的安卓crash:Adapter数据源发生变化但是没有通知ListView。
异常类型: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.
从exception开始追踪研究安卓源代码(6.0.1_r10),探究一下上述crash发生的原因。
先看看ListView.java中在什么位置抛出这个exception:
@Override
protected void layoutChildren() {
......
// Handle the empty set by removing all views that are visible
// and calling it a day
if (mItemCount == 0) {
resetList();
invokeOnItemScrollListener();
return;
} else if (mItemCount != mAdapter.getCount()) {
throw new 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(" + getId() + ", " + getClass()
+ ") with Adapter(" + mAdapter.getClass() + ")]");
}
......
}
在layoutChildren的时候,即对子View进行布局的时候,在主要的逻辑开始之前会判断成员变量