我的一些用户(可能有 50 个)因以下错误而崩溃:
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.
如果我理解正确的话,这是由于在 AsyncTask 的 doInBackground()< 中调用
方法,我需要在 adapter.clear();
和 adapter.addAll(list);
引起的onPostExecute()
中移动它。
问题是我无法重现该错误,所以我不确定它是否已修复。 StackOverflow 上的一些类似问题似乎表明,仅将更新适配器移动到 onPostExecute()
方法并不能解决问题。
有谁知道如何让我的设备每次都发生此错误以确保修复有效?我不明白为什么它在大多数情况下都能正常工作,但有时会导致崩溃。
最佳答案
简单的回答:您忘记调用 adapter.notifyDatasetChanged()
。
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
在后台获取数据并在 onPostExecute()
中更新适配器,因为您永远不应该从后台线程更改适配器的内容。 onPreExecute()
和 onPostExecute()
都在 UI 线程上执行。
关于java - 从后台线程更新适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26125057/