Extending the Application Class & Good Practices

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 Application class, 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 Application class 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 a database.

Another option would be to combine both the use of Application, plus SharedPreferences for example. First try to retrieve the variable from Application instance, if the variable is null, then retrieve it from SharedPreferences.

Using a Singleton approach is not really a bad idea, but it may be troublesome in the cases when being used in a multi-threaded environment where one thread sets a value to a variable and the other thread may over-write that value without any notice.

However, in order to keep application level instances/variables, it is suggested to extend Application class and define it in your AndroidManifest.xml as the default one. Since the application's context is created only once (till the application is running and stays in the memory) when you launch that application, so you may define some variables inside that class to make them availabe anywhere in your application's code using public methods.

Moreover, you may use your application class as Singleton too, since its guaranteed to be created only once when launched.

Need Your Help

How to position a vertical menu as nested <ul> under horizontal parent <li>

html css html-lists

We're really close to solving this one and just need a little help to ties things off. Everything works fine, but how do we get the nested 'ul' to display relative to it's parent 'li' (ie. directly...

Convert an array of tuples into a hash-map in Clojure

clojure map hashmap tuples

I have an array of tuples, where each tuple is a 2 tuple with a key and a value. What would be the cleanest way to convert this array of tuples into a hash-map?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.