發現情況
正在做一個設備控制app,需要阻塞接受下位機發送的can數據,當數據發送過快,10ms一次的時候,app crash 報錯:
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.
原因查找
根據報錯信息找到報錯位置:
protected void layoutChildren() {
*****************************************
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. [in ListView(" + getId() + ", " + getClass()
+ ") with Adapter(" + mAdapter.getClass() + ")]");
}
*****************************************
根據代碼發現 mItemCount != mAdapter.getCount()
分析
原因是由於我在子線程中更新數據,在主線程中更新ui。
比如你在handler處理同步主線程中 爲mItemCount,而這時候子線程add(data),mAdapter.getCount()就加1。
這時候mItemCount != mAdapter.getCount();
解決
把數據更新的操作也放到主線程中。
這樣的話即使1ms發一次數據 app 也不會crash。