What I want to do: run a background thread which calculates ListView contents and update ListView partially, while results are calculated.
W
Several days ago I met the same problem and causes several thousands of crash per day, about 0.1% of users meet this situation. I tried setVisibility(GONE/VISIBLE)
and requestLayout()
, but crash count only decreases a little.
And I finally solved it. Nothing with setVisibility(GONE/VISIBLE)
. Nothing with requestLayout()
.
Finally I found the reason is I used a Handler
to call notifyDataSetChanged()
after update data, which may lead to a sort of:
checkForTap()
/onTouchEvent()
and finally calls layoutChildren()
)notifyDataSetChanged()
and update viewsAnd I made another mistake that in getCount()
, getItem()
and getView()
, I directly use fields in DataSource, rather than copy them to the adapter. So finally it crashes when:
getCount()
and getView()
is called, and listview finds data is not consistent, and throws exceptions like java.lang.IllegalStateException: The content of the adapter has changed but...
. Another common exception is an IndexOutOfBoundException
if you use header/footer in ListView
.So solution is easy, I just copy data to adapter from my DataSource when my Handler triggers adapter to get data and calls notifyDataSetChanged()
. The crash now never happens again.