Home > Researches > Defining Global Variables in Android

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

About these ads
  1. Tom
    March 23, 2012 at 10:18 am | #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.

    • March 23, 2012 at 7:09 pm | #2

      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. Jacek Milewski
    March 29, 2012 at 7:26 pm | #3

    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. May 16, 2012 at 11:46 am | #4

    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. November 6, 2012 at 5:38 am | #5

    thanks for the post.. am an android developer.. here i comes to know that what actually about singleton..

  5. January 14, 2013 at 2:39 am | #6

    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.

  6. silver_man
    January 17, 2013 at 12:27 am | #7

    Thank you for the clearest example out there on how to make this work!

  7. September 26, 2013 at 3:30 pm | #8

    is wrong…it will throw exception
    <manifest
    android:name=".Globals"
    Please correct it

    • sdfdf asf
      February 28, 2014 at 4:04 am | #9

      it must be like this:

  8. September 26, 2013 at 7:49 pm | #10

    I implemented it and i initialize with 0 , it always remains 0

  9. Mukund
    April 9, 2014 at 11:45 pm | #11

    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?

    • April 15, 2014 at 7:22 am | #12

      You should have declared the method setData() in the Globals class (or the class where your “g” object is instantiated from).

  1. March 22, 2012 at 9:10 pm | #1
  2. February 3, 2013 at 8:38 pm | #2
  3. March 12, 2013 at 10:30 am | #3
  4. March 28, 2013 at 1:00 pm | #4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 484 other followers

%d bloggers like this: