Java – how to create a global variable in Android?
See English answers > 12 Android global variables
I've tried to put it in a custom class, but the problem is that if I kill this activity, it will be lost, and I know there's a way to extend the application
So I want to know what is the best way to store global variables?
I must hint:
>Save variable on onsavestate > save it on shareref > Save manually > retrieve manually
thank you
Update: Thank you for your reply If I have only three variables (simple data, such as a Boolean value, a phrase) and need it after the application restarts, should I use shared pref to store it? What are its disadvantages? For example, will it be harmful to the performance? thank you
Solution
You can create global variables in Android by declaring them in a class that extends the application class
Such a thing
class MyAppApplication extends Application { private String mGlobalVarValue; public String getGlobalVarValue() { return mGlobalVarValue; } public void setGlobalVarValue(String str) { mGlobalVarValue = str; } }
MainActivity. java
class MainActivity extends Activity { @Override public void onCreate(Bundle b){ ... MyAppApplication mApp = ((MyAppApplication)getApplicationContext()); String globalVarValue = mApp.getGlobalVarValue(); ... } }
to update
This will keep this value until your application is not destroyed If you want to keep your values saved after the application instance is destroyed, you can use SharedPreferences as the best way to do this
Learn about SharedPreferences here: http://developer.android.com/reference/android/content/SharedPreferences.html