Thomas Morris
Thomas Morris

Reputation: 87

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

Upvotes: 2

Views: 1299

Answers (3)

Steyrix
Steyrix

Reputation: 3226

The first answer may work for you, but in production (where you will have a lot of persistent data objects, used by several contexts) I recommend to use MVVM pattern and Dagger.

Your activities will have different view models, which can hold a reference to some singleton repository (You will implement it by yourself and inject it to view models with Dagger).

The repository itself will be designed to provide or store data, which can be retrieved from databases, shared preferences and etc. Your variable can be stored there too.

Upvotes: 0

alexanderktx
alexanderktx

Reputation: 158

You can use a global static class for this. You will be able to access the class from anywhere and it's not bound to an activity.

public class Constants {
  public static final String DeviceAddress = "XX:XX:XX:XX:XX:XX";
}

Upvotes: 2

Ganesh Pokale
Ganesh Pokale

Reputation: 1594

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"

Upvotes: 2

Related Questions