Defining Global Variables in Android

At some point in your development process you may need to have several variables across application.

In this post I want to describe 2 ways through you can define global variables in Android: using a singleton 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:

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:

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.

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 <application> tag:

<application
   android:name=".Globals"
   .... />

c) Then you can access your global data from any Activity by calling getApplication()

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.”

20 thoughts on “Defining Global Variables in Android

  1. All of this is great but it has a major flaw: if the application process is killed, which will happen almost undoubtedly if you leave the app in the background too long, your singleton will be recreated, and so your private int data will be re set to a default value.
    Trust me, I’ve learned this the hard way and tried a whole bunch of different hacks to make it work, even with the Application class, it is still a problem.
    So in most cases it will be fine, as long as you’re using your app and it’s in the foreground, or in the background for not too long, but I don’t think it’s a risk worth taking, depending on what your app is.
    In a lot of cases your user will leave the app and come back to it later in the day, only to face null exception.
    It’s annoying but the only real solid way to deal with this is to save the data in either the SharedPreferences or the database.
    I still use the Application class to store global data, but my work around is to back it up with on of the two options listed above. I first try to get the variable directly, but if it’s null I try to fetch it from the SharedPrefs or the DB.

    1. Thanks for this comprehensive comment.
      I agree with you that this is a major flaw unseen until you encounter it. I like your approach first to try get the variable directly and if it’s null then fetch it from SharedPrefs or DB. I think I’ll update the blog post to include this as a suggestion.

    2. Four years later I am interested in what you use actually to store your global variables, Tom.
      Please, can you share some link of one of your recent projects?
      I am new in Android. I also was thinking in request a variable, and take it from sharedPreferences when null.

      But, I have to use (Globals) getApplication(); in each method of my activities that requires global data?
      Why don’t use static methods and something like this: Globals.getMyVariable();

      Thank you all.

      1. Honestly I am no longer supporting this way of storing global data. None of my projects extend Application class with the single purpose of storing global data.
        The alternatives are: storing the data in SharedPreferences, properly save and restore the Activity/Fragment state, retained Fragment.

        “Why don’t use static methods and something like this: Globals.getMyVariable()”: you certainly can use, just be aware of the implications, eg.: static data members live for the live of the process.

        Here’s a link to one of my projects: https://github.com/vgrec/Explore

  2. Actually the problem with singleton may also be that in android You actually don’t know when the app is destroyed, so singleton may remain. Which is in some cases unwanted

  3. there is one more problem 😦 in apps with more then one activity – each activity has OWN SharedPrefs, so it is hard to get GLOBAL value that is same in all activity. I just came to this problem, and to your blog. hope I will find the answer, and come back here with some good news

  4. Thank you for sharing knowledge. Science is very useful for me, and of course also benefit others. I hope you can always update the article so that I can always get a new science. Once again I thank you. Good luck to you.

  5. Hi Veaceslav,
    Thank you for this. Now I can get the globally stored value.
    Is there a special way of using setData? In my code I am trying to use g.setData(112) but it doesn’t even compile.
    It says cannot resolve setData.

    Please correct me if I am not using this correctly?

Leave a comment