The content of the adapter has c

2017-04-08  本文已影响551人  黄海佳

扫描android视频文件,展示列表的时候,突然报了下面的错误

FATAL EXCEPTION: main
Process: com.haijia.demo, PID: 15355
java.lang.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.

其中错误描述:

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.

的意思大体是,你的adapter的内容变化了,但是你的ListView并不知情。请保证你adapter的数据在主线程中进行更改!

修改办法
private class DeviceAdapter extends BaseAdapter {  
  
    private LayoutInflater inflater;  
    private ArrayList<Device> devices;  
  
    public DeviceAdapter() {  
        inflater = LayoutInflater.from(mContext);  
    }  
  
    @SuppressWarnings("unchecked")  
    public void setDeviceList(ArrayList<Device> list) {  
        if (list != null) {  
            devices = (ArrayList<Device>) list.clone();  
            notifyDataSetChanged();  
        }  
    }  
  
    public void clearDeviceList() {  
        if (devices != null) {  
            devices.clear();  
        }  
        notifyDataSetChanged();  
    }  
  
    @Override  
    public int getCount() {  
        return devices == null ? 0 : devices.size();  
    }  
以下略)  

相对于原来,我做了两项改动:

1.将所有数据“完全”保存在adapter内部,即使有外部数据进入,也会用.clone()重新生成副本,保证了数据完全是由adapter维护的。

2.保证所有setDeviceList()/clearDeviceList()是从主线程里调用的,如何保证是从主线程中调用的呢:

a.调用Activity.runOnUIThread()方法;

b.使用AsyncTask。

上一篇下一篇

猜你喜欢

热点阅读