安卓探究ListView+Adapter数据在工作线程中更新引发的crash以及解决方法(一)

本文分析了一个常见的Android Crash:在ListView和Adapter配合使用时,由于数据源在工作线程中修改而未通知ListView导致的IllegalStateException。通过对Android源码的追踪,发现该异常发生在ListView的layoutChildren方法中,由于mItemCount与Adapter的当前count不一致。异常产生的原因是UI线程绘制View时,工作线程更新了数据,而在布局过程中检查到数据变化,从而抛出异常。
摘要由CSDN通过智能技术生成

第一部分 crash描述及原因分析

 

 

在ListViewAdapter搭配使用时,有一个经典的安卓crashAdapter数据源发生变化但是没有通知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进行布局的时候,在主要的逻辑开始之前会判断成员变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值