Defining Global Variables in Android

Thursday, September 18, 2014

In this post I want to describe 2 ways through you can define global variables in Android: using asingleton class, and by extending the Android’s Application class.
1. Using a Singleton class
One of the simplest ways (it does not mean that is one of the best) to have global variables is to declare a singleton class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Globals{
   private static Globals instance;
   // Global variable
   private int data;
   // Restrict the constructor from being instantiated
   private Globals(){}
   public void setData(int d){
     this.data=d;
   }
   public int getData(){
     return this.data;
   }
   public static synchronized Globals getInstance(){
     if(instance==null){
       instance=new Globals();
     }
     return instance;
   }
}
To use this class you get an instance first, and then do what you want with data:
1
2
3
4
5
Globals g = Globals.getInstance();
g.setData(100);
....
int data=g.getData();
Notice that we do not instantiate the object by calling “new”, in fact this wouldn’t be allowed as we declared the constructor private, so its not visible. Instead we call the getInstance() method and return our static object.
2. By Extending the Application class
The second way to define global variables is by extending the Application class. This is the base class for maintaining global application state.
a) Create a new class that extends Application.
1
2
3
4
5
6
7
8
9
10
11
public class Globals extends Application{
   private int data=200;
   public int getData(){
     return this.data;
   }
   public void setData(int d){
     this.data=d;
   }
}
b) Add the class to the AndroidManifest file as an attribute of tag:
1
2
3
<application
   android:name=".Globals"
   .... />
c) Then you can access your global data from any Activity by calling getApplication()
1
2
Globals g = (Globals)getApplication();
int data=g.getData();

I said that using the Singleton pattern it’s one of the simplest ways to define global variables, but I mentioned also that it does not mean that it’s one of the best ways to do it. In fact this is quite a controversial subject.
You may believe that when a static variable is initialized it stays so for the entire life of the application, however this does not seem to be true everytime. Sometimes, there are situations when some static variables bound to activities happens to be uninitialized even they have been initialized.
This makes the static singleton approach not one of the best for keeping global variables, though the official Android documentation seems to encourage using them: “There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way.”