Android: Modifying adapter content from a background thread
I've read up quite a bit on the exception thrown while using BaseAdapter, but i can't seem to find an alternative solution: Make sure the content of your adapter is not modified from a background thread
What i want to achieve is to keep a copy of a message queue in memory, and use this message queue to populate th开发者_StackOverflow社区e BaseAdapter for my ListView. The reason im doing this is that the message queue will keep getting messages from a socket even when the ListView is not currently present (for example a chat window).
The problem comes when i have the Activity with the ListView in foreground, BaseAdapter binded to the message queue's data, and a message comes in the socket. Adding the new message into the queue will throw the exception mentioned above. Unless i pre-populate my BaseAdapter with the message queue (as in the BaseAdapter having its own message queue) and updating both of them when a new message come in, i can't really find a way around this issue.
I don't really want to double up the effort on keeping those 2 queues up-to-date like this, surely there is a better way of doing this? Send broadcasts around doesn't work either because of the potential delay in the adapter serving a scroll and the notifyDataSetChanged call is made.
Use a Handler
to modify the "message queue" from the main application thread.
I had this problem as well. It turns out I was recreating my adapter for new data but the old adapter was still set to the listview and would occasionally cause a crash. So I do something like this when I need to recreate the adapter:
//Clear adapter's array
if (!array.isEmpty()) { array.clear(); }
if (adapter != null) { adapter = null; }
setListAdapter(adapter);
//Later code
//array gets repopulated
//adapter gets recreated
setListAdapter(adapter);
精彩评论