I used to use public static
member variables in order for the starting Activity
to be able to read the values from the previous Activity
. I know that it is not a good practice and that it involves risks and limitations like having several instances of the current Activity
and get the wrong value from the static variable.
Now I use Parcelable
and pass the parameters in Bundle, but it is a burden sometimes. For example, in my current project I have a ExpandableListView
and the groups/children stored in a Map<group name, List<child>>
. This list is in a Fragment
which is inside a TabHost
in a FragmentActivity
. Clicking on a child in the list will launch another FragmentActivity
with the same structure (TabHost
and a Fragment
inside). From this Fragment
you can edit the child. The problem comes when I need to notify the list that the child has changed. Following the best practices I decided to use a Broadcast
to send the modified child to the first Activity
, and let it update the list.
If, instead of a Parcelable
, I'd use a public static
variable I just would need to call notifyDataSetChange()
in the list to refresh because the actual object instance in the Map
was modified. With the Parcelable
, even if the object is the same, when it is modified is a different variable in a different memory region. When the first Activity
receives the Broadcast
, it needs to loop through all the childs in all the groups to check if it's the same object and replace itself with the broadcasted Parcelable
.
What am I doing wrong? Or is it supposed to be like this? With this kind of issues I am really tempted to go the public static way :-P
PS: Something like this. Long arrow is Broadcast, short arrow is Activity telling the Fragment to replace the child in the Map and refresh the list.
Fragment Activity <----
| |
TabHost | |
| |
Fragment <--| |
|
Fragment Activity |
|
TabHost |
|
Fragment --------------
From your first activity, you can startActivityForResult
. Your second activity can then return the updated dataset. Your first activity can then reassign the data map to whatever onActivityResult
picks up and you can use notifyDataSetChanged
.