12
I have a Activity
that displays a ListView
, to which a Adapter
"backed by" a ArrayList
global. If I add an element to that ArrayList
, ideal is to do it in the main thread and immediately call Adapter.notifyDataSetChanged()
in order to avoid a "Illegalstateexception: The content of the Adapter has changed but Listview Did not receive a notification". But this ArrayList
is changed by a secondary thread, run by a Service
which is not always coupled to Activity
and therefore does not always have a reference to Adapter
so that you can ask the main thread to perform these two operations. And then when (I imagine) the main thread comes across the altered list, the exception happens.
I see two ways to solve this:
Make the
Adapter
global so I can call you anytime I want.Create a deep copy of the list and associate the copy to the
Adapter
. So that when the original list is changed the copy remains untouched until the main thread needs to display the change (inActivity.onResume()
, for example). Then I change the copy from the original and callnotifyDataSetChanged()
.
The disadvantage of the first in my opinion is to make the code confused with the presence of an object outside its correct scope, because the right strictly speaking would keep it only for the life period of the Activity
who uses it. The disadvantages of the second one are the redundancy that appears to be unnecessary and the extra memory occupation (although the list is not very large, at most 500 objects of some 12 fields each). Are there other advantages and disadvantages in these two options? Is there a third option?
I also posted on ONLY in English.
We are discussing how to use tags in this case: http://meta.answall.com/questions/468/existem-tags-implicitas
– Maniero