Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible, and what is the best strategy, to pass objects by reference from one Activity to the next?

I have a simple Android application that uses an instance of a class, let's call it DataManager, to manage access to the domain classes in a Façade-like way. I initially designed it as a singleton which could be retrieved using static methods but I eventually got irritated with the messiness of my implementation and refactored to what I reckoned was a simpler and cleaner idea.

Now the idea is that for each file that is opened, one DataManager is created, which they handles both file I/O and modification of the domain classes (e.g. Book). When starting a new Activity, I pass this one instance as a Serializable extra (I haven't got on to using Parcelable yet, but expect I will when I have the basic concept working), and then I grab the DataManager from the Intent in the onCreate() method of the new Activity.

Yet comparison of the objects indicates that the object sent from one activity is not identical (different references) to the object retrieved from the Bundle in the second Activity. Reading up on Bundle (on StackOverflow, etc.) suggests that Bundles cannot do anything other than pass-by-value.

So what is likely to be the cleanest and safest strategy for passing an object between Activities? As I see it I could

  1. Forget about passing by reference and live with each Activity having its own DataManager object. Pass back the new DataManager every time I close an activity so that the underlying activity can use it. (The simple solution, I think.)

  2. Go back to using a singleton DataManager and use a static method to get it from each Activity. (Not keen on using singletons again.)

  3. Extend Application to create a sort of global reference to DataManager. (Again, not keen on the idea of globals.)

Is that a fair summary? Is there some other healthy strategy I could use?

like image 798
Spinner Avatar asked Oct 11 '22 05:10

Spinner


1 Answers

Another approach would be to create a service. The first activity would start the service and bind to it, when you launch a new intent, unbind the first activity and when second activity starts, bind to the service.

This way you don't have to ever stop the service or worry about passing data between activities.

like image 163
Ljdawson Avatar answered Oct 13 '22 00:10

Ljdawson