I am new to Android and getting a bit confused in between Application class and Singleton.As I understood, it's not safe to store/maintain global value in Application or singleton class due to Out Of Memory Exception.So, any solution for that other than using persistence storage.and Apart from that, in which cases Application class useful?
-
Refer https://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android – Nikhil Lotke Jan 02 '18 at 09:31
-
1prefer singleton over application, a test is that use a variable with setter and getter,to set in one activity and to get in others, then go home, shuffle through some apps and come back to your app, if Application you used then you get null value but in Singleton, you might not get null ..just saying – hemen Jan 02 '18 at 11:15
1 Answers
I very much recommend singletons. If you have a singleton that needs a context, have:
MySingleton.getInstance(Context c) {
//
// ... needing to create ...
sInstance = new MySingleton(c.getApplicationContext());
}
I prefer singletons over Application because it helps keep an app much more organized and modular -- instead of having one place where all of your global state across the app needs to be maintained, each separate piece can take care of itself. Also the fact that singletons lazily initialize (at request) instead of leading you down the path of doing all initialization up-front in Application.onCreate() is good.
There is nothing intrinsically wrong with using singletons. Just use them correctly, when it makes sense. The Android framework actually has a lot of them, for it to maintain per-process caches of loaded resources and other such things.
Also for simple applications multithreading doesn't become an issue with singletons, because by design all standard callbacks to the app are dispatched on the main thread of the process so you won't have multi-threading happening unless you introduce it explicitly through threads or implicitly by publishing a content provider or service IBinder to other processes.

- 309
- 3
- 9