Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 364
Teovald Avatar asked Sep 08 '12 21:09

Teovald


People also ask

What is an application class?

The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.

Where is Android App application?

From anywhere. Swipe up from the bottom of your screen to the top. If you get All Apps , tap it. Tap the app that you want to open.

What is ANR used for in Android?

Application Not Responding (ANR) errors are triggered when the UI thread of the application is not responding for more than 5 seconds. You can read more about ANRs and diagnosing ANRs in the Android documentation. Additionally, Crashlytics can help pinpoint specific problematic threads.

What are classes in Android?

A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.


1 Answers

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.

like image 85
waqaslam Avatar answered Oct 10 '22 15:10

waqaslam