Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication with parent Activity, refreshing parent activity

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.

  • I don't like this one because I am not able to send the message directly

2) Always refresh data in activity A on resume.

  • Isn't that waste of processing?

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

  • There is no global state (am I right?). We shouldn't do that as there is an extra abstraction layer (intents).

5) use getParent() to use parent activity

  • The parent activity may be destroyed and recreated on return

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?

like image 822
user364622 Avatar asked Nov 18 '25 08:11

user364622


1 Answers

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.

  1. Activity A registers a broadcast receiver to some custom action "com.mypackage.datachanged".

  2. 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).

like image 165
Ran Nachmany Avatar answered Nov 20 '25 20:11

Ran Nachmany



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!