应用程序因未处理的异常而崩溃:适配器的内容已更改但 ListView 未收到通知

App crashed because of Unhandeled exception: The content of the adapter has changed but ListView did not receive a notification

Full exception : Unhandeled exception: 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. [in ListView(2131296364, class android.widget.ListView) with Adapter(class elfar.insitemobile.Tabs.EventTable$EventTableListAdapter)]

它只在应用程序启动时发生(列表正在更新未决事件),而且它只是偶尔发生。 我注意到当应用程序启动时列表中有很多未决事件要更新时会发生这种情况。如果只有很少的项目要更新,则不会发生。

我尝试 运行 在一个线程中更改这些列表并在每次更新后放置 notifyDataSetChanged(),但它仍然发生。

嗯,这看起来很明显,但它经常发生 - 确保您没有在 UI 线程之外向 ArrayList(或您正在使用的任何其他列表)添加项目。所以一定要在UI线程中添加项目并调用notifyDataSetChanged()。这个 SO post 可能会有进一步的帮助:Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

希望这对您有所帮助!

更新:我通过将 Add 和 Remove 函数的调用插入到使用 mainLooper 创建的处理程序的新 Runnable 中解决了以下问题。

private static Handler mHandler = new Handler(Looper.getMainLooper());

mHandler.post(new Runnable() {

        @Override
        public void run() {
            lMessages.add(0,message);
            ...
}