java - 从后台线程更新适配器

标签 java android

我的一些用户(可能有 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/

相关文章:

android - 来自 AWS Android SDK 示例应用程序的 DynamoDB 表不在控制台中

java - 堆转储中有很多 hibernate 查询。我该如何限制?

使用 JLine 的 Java 控制台自动完成

java - hibernate Eclipse 插件

java - Android 与从另一个 Activity 启动的位置管理器通信

android - 谷歌 Espresso 问题跟踪器问题去了哪里?

android - 如何在 Android 上使用带有 V8 的 Chrome 调试器

android - TabWidget 在 Android 2.1 设备中看起来不正确

java - 交错两个字符串数组

java - 为什么在扩展类时会出现 ClassCastException?