关于Adapter大家都会用,但是用的时候常常会出现:
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.
意思很简单,就是说adapter内容修改数据后,adapter没有收到通知。让你确保内容修改是在主线程里操作。
其实出现以上问题的原因很明显,我们在处理数据的时候,可能耗时比较长,这时,我们就会单独开一个线程来处理数据,但是,这个数据正好又被adapter引用了,那么问题就来了。。。。单开的线程肯定不是主线程啊,自然就会出现这个错误了。
其实归根结底就是adapter使用不规范,所以这里推荐大家一个框架,直接将数据修改放到adapter内部,notifyDataSetChanged也放在数据改变后直接执行。这样既减少了代码量,而且可以很好的规避以上错误。废话不多说,直接上代码
private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<String> myData;
public MyAdapter() {
this.inflater = LayoutInflater.from(Context);
}
public void setMyData(ArrayList<String> list) {
if (list != null) {
myData = (ArrayList<String>) list.clone();
notifyDataSetChanged();
}
}
public void clearMyData() {
if (myData != null) {
myData.clear();
}
notifyDataSetChanged();
}
public void removeMyData(String str){
if (myData != null) {
myData.remove(str);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return myData == null ? 0 : myData.size();
}