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
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.)
Go back to using a singleton DataManager
and use a static method to get it from each Activity
. (Not keen on using singletons again.)
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?
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.
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