I am not able to find best solution to the situation where child activity changes data of parent activity.
I have activity A containing a list of items. Activity A starts activity B to show details to the user. User can run action and create activity C. Activity C creates new elements for the list in activity A.
The data are held in database so there is no problem with passing the data. I'm interested only in notification.
What is best solution to notify activity A that the data have been changed?
Currently I am aware of 2 solutions:
1) Return result by activity B and C with startActivityForResult(..) and Extras. The result would contain message "datachanged" -> true / false.
2) Always refresh data in activity A on resume.
3) Send Intent from activity C to activity A (broadcasts)
The solution I have found which are almost certainly wrong:
4) Save in some global state
5) use getParent() to use parent activity
Isn't there some other more light-weighy messanger system beetween activities? Something like Handler and Messanger in Activity-Service communiction. Maybe there shouldn't be one because it's against design?
Another option is to use broadcasts or localbroadcasts in order to send notification / event from C to A.
It will look something like: 1. Activity A loads the data in onCreate.
Activity A registers a broadcast receiver to some custom action "com.mypackage.datachanged".
Activity C sends broadcast intent with the same action once it changes the data.
This way - if Activity A is still kept in memory - it's receiver will catch the event and will reload your list when needed. If activity A is killed - it will auto refresh the data automatically when it is recreated.
Some notes: 1. Do not forget to un-register the receiver in Activity A's onDestroy. 2. You can use local broadcasts instead of broadcasts. The advantage:better performance and security (your intent will never leave your app).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With