0

i am new to android development and i was trying to use a global variable across two activities. So how do i do the same using setter and getter? or is there a better way? Please do help me! Thanks in advance! Sidharth

Sidharth MA
  • 85
  • 13

2 Answers2

1

The easiest way to do this would be to pass the variable to the second activity in the intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("variableKEY", variable);
startActivity(intent)

Access that intent on next activity

String s = getIntent().getStringExtra("variableKEY");

The docs for Intents has more information (look at the section titled "Extras").

From here

Community
  • 1
  • 1
Nirel
  • 1,855
  • 1
  • 15
  • 26
1

For global variable :

  1. Use can use SharedPreference, which will save the value till you uninstall the application and can be accessed from anywhere within application using context.

  2. Extend Application class, and declare the global variable inside it and add getter and setter methods.

And in your activity :

    YourApplication yourApplication = (YourApplication) getApplicationContext();
    yourApplication.setGlobalValue(10);
    yourApplication.getGlobalValue();

Create class :

 class YourApplication extends Application {
    private Integer globalValue;

    public Integer getGlobalValue() {
        return globalValue;
    }

    public void setGlobalValue(Integer value) {
        globalValue = value;
    }
}
Vinodh
  • 1,069
  • 2
  • 10
  • 22