异步加载Listview The content of the adapter has changed but ListView did not receive a notification

来源:互联网 发布:虚拟定位是什么软件 编辑:程序博客网 时间:2024/06/09 14:56

错误

The content of the adapter has changed but ListView did not receive a notification

原因

在Android开发过程中,使用了大量的ListView,发现这个错误偶尔会出现。特别是做压力测试的时候,不停的点击刷新,更容易出现这个错误。代码中已经使用了Adapter的notifyDataSetChanged()方法通知UI更新了,但是还是会出现这个错误。究其根本原因,还是线程之间同步的问题。比如,线程1更新了Adapter中的内容,却还没有来得及通知内容已经更新,就又有线程2更新了Adapter中的内容,这个时候如果线程1再通知内容更新,就会出现上述异常了

解决方法

ListView的滚动有三种状态
第一是静止状态,SCROLL_STATE_IDLE
第二是手指滚动状态,SCROLL_STATE_TOUCH_SCROLL
第三是手指不动了,但是屏幕还在滚动状态。SCROLL_STATE_FLING

在静止状态 进行adapter 更新即可

示例代码如下:

class ListOnScrollListener implements AbsListView.OnScrollListener {        private int visibleLastIndex;        private LegworkAdapter adapter;        private RTPullListView listView;        private View footer;        public ListOnScrollListener(LegworkAdapter adapter, RTPullListView listView, View footer) {            this.adapter = adapter;            this.listView = listView;            this.footer = footer;        }        @Override        public void onScroll(AbsListView view, int firstVisibleItem,                             int visibleItemCount, int totalItemCount) {            visibleLastIndex = firstVisibleItem + visibleItemCount - 1;/* 如果滚动到最后一条 */        }        @Override        public void onScrollStateChanged(AbsListView view, int scrollState) {            if (adapter != null) {                int itemsLastIndex = adapter.getCount(); // 数据集最后一项的索引                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == itemsLastIndex) {                    //静止状态在进行adapter更新 否则异常退出                    adapter.notifyDataSetChanged();                    if (page < totalpage) {                        listView.addFooterView(footer);                        page = page + 1;                        flag = true;                        SharedPreferenceUtils sharedPreferenceUtils = new SharedPreferenceUtils(LegworkActivity.this);                        String subUrl = sharedPreferenceUtils.getString(SharedPreferEnum.SUB_URL.name());                        int empId = sharedPreferenceUtils.getInt(SharedPreferEnum.EMP_ID.name());                        new Task().execute(subUrl, String.valueOf(empId), String.valueOf(page), String.valueOf(Constant.PAGE_SIZE));                    }                }            }        }    }



0 0
原创粉丝点击