I am considering using the android Application class as a place to store temporary state and common code shared by other (fragment) activities in the app.
I would like to get more feedback as to whether it is a good place for:
- Shared constants like ID’s, pref key names, etc.
- Global variables (i.e. setters/getters) reflecting current UI state, navigation, selected fragment, and, in general, temporary data that does not need to be persisted.
- Hooks for persisting data when certain conditions are triggered.
- Updating the UI after preference changes.
- Providing an easy way to access the context from anywhere in the app, including code where
getApplication()is not available, e.g. via a static getter such asMyApp.getApp(). - Common methods that need the visibility of the global state variables and which would become too cumbersome to move away to dedicated classes.
What else would be appropriate/useful/handy to have in the activity class? What would not be a good idea to keep in it and what would be the best alternatives? And finally, what you have found Application to be best used for in your apps?
I generally create a constants file called C for this, as its better for readability.
C.SHARED_PREFSis easier to understand thatApplication.SHARED_PREFSIMHO.This would be better off in the Activity or component which it concerns (for example, the UI state of an Activity should probably stored in the icicle bundle, or within that instance of the Activity).
This should be fine.
Again, I feel this would be better off in the respective component.
This would work, but be careful of memory leaks. You should generally pass the context in as a parameter when calling the method from an Activity or Service or whatever. Less chances of a memory leak.
I feel it would be better to make the effort of dedicated classes, as when your app grows in features and size, this will become difficult to maintain.