Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a global variable to use in all activities

Tags:

java

android

I am creating a custom class in main application class. Lets say My mainAccount.

Now, i am creating many activities. I want to mainAccount variable in every activity, how can i do that? One way is to put in intent and pass to each activity. Is there any better way, like making it global etC?

Best Regards

like image 971
Muhammad Umar Avatar asked Mar 08 '12 04:03

Muhammad Umar


2 Answers

Look up Singleton classes. Basically, you want something like this.

public class Singleton {
   private static Singleton instance = null;
   protected Singleton() {
      // Exists only to defeat instantiation.
   }
   public static Singleton getInstance() {
      if(instance == null) {
         instance = new Singleton();
      }
      return instance;
   }
}

Then, for any class that needs access to the class, call:

Singleton var=Singleton.getInstance();

This is essentially global, without most of the negative consequences of global variables. It will ensure that only one object of that class can exist, but everyone who needs it can access it.

like image 195
PearsonArtPhoto Avatar answered Oct 16 '22 21:10

PearsonArtPhoto


You can use "singleton" class, or "static" class (if you don't need to initialize it, instantiate or inherit or implement interfaces).

Singleton class:

   public class MySingletonClass {

        private static MySingletonClass instance;

        public static MySingletonClass getInstance() {
            if (instance == null)
                instance = new MySingletonClass();
            return instance;
        }

        private MySingletonClass() {
        }

        private String val;

        public String getValue() {
            return val;
        }

        public void setValue(String value) {
            this.val = value;
        }
    }

String s = MySingletonClass.getInstance().getValue();

Static class:

public  class MyStaticClass {
    public static String value;
}

String s = MyStaticClass.value;

like image 24
live-love Avatar answered Oct 16 '22 20:10

live-love