Search code examples
androidstringandroid-studioandroid-activityglobal-variables

Android Studio global static variable accessible from multiple activities


In android studio I want to have a static (unchanging) variable which, I can obtain from multiple activities. My application has several activities:

  1. Login Activity
  2. Home Activity
  3. Sub Activity 1
  4. Sub Activity 2
  5. Sub Activity 3

Within these activities I need to check a value to execute different code depending on the value. In my case it is a device address. I use this device address in two places and therefore, presently define it in 2 separate places. I know this is an incorrect way of doing this. So I want to define it once and access it from both activities e.g. Home Activity and Sub Activity 1.

I want to know where I can define this variable and then how I include it. An example of the variable is : private String Device_Address = "XX:XX:XX:XX:XX:XX";

One idea is should I make it a public static variable from the home activity and then import the variable to the sub activity?

Thanks


Solution

  • Declare veriable in Application class

    public class App extends Application
    {
       private boolean isActive= false;
    
     public boolean getisActive() {
            return isActive;
        }
    
        public void setisActive(boolean _isActive) {
            this.isActive= _isActive;
        }
    
    }
    

    and Usage is

    App.getInstance().getisActive()
    

    Register App in Manifest

    <application
            android:name=".App"