Android的ListView的IllegalStateException异常:"适配器的内容发生了变化,但ListView控件没有收到通知"适配器、控件、发生了、异常

2023-09-11 11:48:01 作者:帶著夢想去旅行

我想做什么:运行一个后台线程,其计算的ListView内容和更新的ListView部分,而结果计算

What I want to do: run a background thread which calculates ListView contents and update ListView partially, while results are calculated.

我知道我必须避免:我我不能乱用,从后台线程ListAdapter内容,所以继承的AsyncTask和onProgressUpdate公布结果(条目添加到适配器)。我的适配器使用结果对象的ArrayList,在这些的ArrayList的所有操作都是同步的。

What I know I have to avoid: I cannot mess with ListAdapter contents from background thread, so I inherited AsyncTask and publish result (add entries to adapter) from onProgressUpdate. My Adapter uses ArrayList of result objects, all operations on those arraylists are synchronized.

研究别人:有非常有价值的数据这里。我也遭受了几乎每天都崩溃了一批〜500个用户,当我在onProgressUpdate添加 list.setVisibility(GONE)/trackList.setVisibility(可见)块,崩溃降低通过10倍,但没有消失。 (有人建议在answer )

Research of other people: there is very valuable data here. I also suffered from almost daily crashes for group of ~500 users, and when I added list.setVisibility(GONE)/trackList.setVisibility(VISIBLE) block in onProgressUpdate, crashes lowered by a factor of 10 but not disappeared. (it was suggested in answer )

什么我有时:请注意,它真的发生了很少(一3.5K的用户每周一次)。但我想摆脱这种错误完全。下面是部分堆栈跟踪:

What I got sometimes: please notice, it happens really rarely (once a week for one of 3.5k users). But I'd like to get rid of this bug completely. Here is partial stacktrace:

`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(2131296334, class android.widget.ListView) with Adapter(class com.transportoid.Tracks.TrackListAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1432)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:2062)
at android.widget.ListView.onTouchEvent(ListView.java:3234)
at android.view.View.dispatchTouchEvent(View.java:3709)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:852)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
[...]

帮助?不再需要,请参阅下面

Help? Not needed anymore, see below

最后的答案:事实证明,我打电话 notifyDataSetChanged 每5插入,避免闪烁和突然列表更改。它不能做这样的方式,总是通知适配器时,基地名单的变化。此错误是长了我吧。

FINAL ANSWER: As it turned out, I was calling notifyDataSetChanged every 5 insertions to avoid flickering and sudden list changes. It cannot be done such way, always notify adapter when base list changes. This bug it long gone for me now.

推荐答案

我有同样的问题。

我将项目添加到我的的ArrayList UI线程之外。

I was adding items to my ArrayList outside the UI thread.

我都添加的项目键,名为 notifyDataSetChanged()在UI线程和我解决了这一点。

I both added the items and called notifyDataSetChanged() in the UI thread and I resolved this.