刷新Adapter的时候。加载绑定在其上面的数据容器的时候,最好是线程里new 个新的对象。然后在UI线程中装载进去,然后notifyDataSetChanged();
eg:
子线程:
ArrayList<File> results = new ArrayList<File>();
if (file != null && file.listFiles() != null) {
for (File file2 : file.listFiles()) {
if (file2.isDirectory()) {// 文件夹
results.add(file2);
} else if (file2.getName().endsWith(".mp3"))// mp3文件
results.add(file2);
}
}
return results;
UI线程:
files.clear();
files.addAll(results);
MyAdapter.notifyDataSetChanged();
切记不可在线程中直接files.add(对象),容易报数据已更改,adapter没刷新exception、
子线程:
eg:
子线程:
files.clear();
if (file != null && file.listFiles() != null) {
for (File file2 : file.listFiles()) {
if (file2.isDirectory()) {// 文件夹
files.add(file2);
} else if (file2.getName().endsWith(".mp3"))// mp3文件
files.add(file2);
}
}
UI线程:
MyAdapter.notifyDataSetChanged();
E/AndroidRuntime(7323): 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. [in ListView(2131296280, class android.widget.ListView) with Adapter(class com.aa.MyAdapter)]
因为数据在子线程中已经被修改,但是没有使用Handler通知更新,而ListView有自己的监听数据更改的逻辑,能得到数据已经更改,所以每次与ListView绑定的数据更改,必须立刻执行notifyDataSetChanged();I