When I’m writing a method or using a member variable, I often find I need to share them across an app. But where should they go?
I can subclass Activity, but that falls over as soon as I use a MapView and am forced to use MapActivity, so not all my activities inherit from my subclass. Is there I way around this?
Where inheritance isn’t applicable, I am tending to put generic methods and member variables into a subclass of the Application object, but I’m finding it’s creating a mess of code as every class needs to either grab access to the application object through via context, or I have to pass it down.
I suspect I would be better off creating MyApplication.getInstance() and keeping everything in a singleton, instead of passing the application object down through the app classes. but before I wanted to see what you guys had to say.
If you want to access the “Global Singleton” outside of an activity and you don’t want to pass the
Contextthrough all the involved objects to obtain the singleton, you can just define, as you described, a static attribute in your application class, which holds the reference to itself. Just initialize the attribute in theonCreate()method.For example:
One example with resources: Because subclasses of
Applicationalso can obtain the Resources, you could access them simply when you define a static method, which returns them, like: