Home » Android » java – Declaring a global variable to use in all activities

java – Declaring a global variable to use in all activities

Posted by: admin June 15, 2020 Leave a comment

Questions:

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

How to&Answers:

Have you thought about using preferences?
A great resource for more info is.
http://mobile.tutsplus.com/tutorials/android/android-application-preferences/

Or you can create a class that extends application as demostrated by
http://www.helloandroid.com/category/topics-covered/global-variables

Answer:

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.

Answer:

Just define an Abstract class with those variables and methods whichever you want to access in activities.

For example:

public abstract class BaseActivity extends Activity
{
  //static variables
  // static methods
}

Now extends this BaseActivity class in your all activity:

public class HelloAndroid extends BaseActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Answer:

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;