I have been told recently that extending the Application Class in order to use it as a Singleton was a bad practice but without any explanation.
So what are the potentials problem behind the use of this class ? I have seen it used in many projects.
Also, if using the Application Class is a bad idea, what are the alternatives to store application level variables ?
The problem with using a Singleton class, as well as extending the
Applicationclass, is that if the application process is killed – which is very likely to happen when the app is left too long in background – the object will lose all your data.However, using
Applicationclass may be a good option in cases when your app is in foreground or does not stay to much in background (although not 100% risk free).As an alternative, you could save the data into
SharedPreferences, or if your object is more complex, save it in adatabase.Another option would be to combine both the use of
Application, plusSharedPreferencesfor example. First try to retrieve the variable fromApplicationinstance, if the variable is null, then retrieve it fromSharedPreferences.