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
Asked
Active
Viewed 2,147 times
2 Answers
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").
1
For global variable :
Use can use SharedPreference, which will save the value till you uninstall the application and can be accessed from anywhere within application using context.
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
-
Thank You so much vinod, it helped me. – Sidharth MA Dec 07 '16 at 08:52
-
@SidharthMA : no problem. Enjoy !! – Vinodh Dec 07 '16 at 08:54