《每日一剂》适配器刷新报错adapter.notifyDataSetChanged()解决

在使用ListView过程当中,有时会出现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.java

缘由是给ListView设置的adapter,修改数据源时放在了非UI线程中去执行,在主线程中调用adapter的notifyDataSetChanged()方法,有时会抛出此异常,(亦即,当ListView缓存的数据Count和ListView中Adapter.getCount()不等时,会抛出该异常。)所以,修改adapter数据源时须要放在主线程中去执行,这里给出两种思路。缓存

提早将adapter的数据全清空了adapter.getDateList.clear(),且并无及时调用adapter.notifyDataSetChanged(),致使ListView没有数据而抛java.lang.IllegalStateException这个异常。ide

用户体验:刷新页面或下拉刷新,手指点击任意UI,致使崩溃。线程

解决作法:将adapter.getDateList.clear()与adapter.notifyDataSetChanged()写在一块儿get

解决方法:it

让适配器和数据一块儿执行,在同一线程。好比io

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        list.clear();
        list.addAll(toLearnBean.getData().getArrCourse());
        adapter.notifyDataSetChanged();
    }
});

1.修改数据时能够为adapter的数据源复制一个副本,在子线程中修改副本的数据便可,而后在主线程中将副本赋值给adapter数据源便可。thread

2.直接在主线程中修改adapter的数据源。经过Activity.runOnUiThread()方法,Handler机制和AsyncTask都可实现。用户体验

相关文章
相关标签/搜索