如何在Android中创建一个全局变量? [英] How to create a global variable in android?
问题描述
在我的android应用程序,我需要一个地方放置可变成员id。
问题是,它是从在线API,我需要找到一种方式来存储/检索它
我试图把它放在一个自定义类,但问题是,如果我杀了活动,它会失去,我也知道有一种方法来扩展应用程序。
所以我想要知道什么是存储全局变量的最好方法?
我必须隐瞒:
- 将变量保存在onSaveState上
- 将其保存在sharepref上
- 手动保存
-
更新:
感谢您的回复。如果我只有3个变量(简单数据,例如一个布尔,一个短语),我需要它在应用程序重新启动后,我应该使用共享预存储它吗?它的缺点是什么?例如它会对性能有害吗?感谢解决方案您可以在Android中创建全局变量,通过在类中声明它们扩展
这样的东西。
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();
...
}
}
更新
这将保存该值,直到应用程序不被销毁。如果你想保存你的值,即使你的应用程序实例销毁
后,你可以使用SharedPreferences
最好的方法来做到这一点。
从这里了解
SharedPrefernces
: http://developer.android.com/reference/android/content/SharedPreferences.htmlIn my android application I need a place for putting the variable member id . The problem is , it is getting from the online API and I need to find a way to store / retrieve it
I have tried to put it in a custom class , but the problem is , it will lose if I kill the activity, I have also know that there is a way to extends the application.
So I would like to know what is the best way to store global variable?
I have to implment:
- Save the variable on onSaveState
- Save it on sharepref
- Save it manually
- Retrieve it manually
Thanks
Update: Thanks for reply. If I have just 3 variable (simple data e.g. a boolean , a phrase ), and I need it after app restart , should I simply use share pref to store it? What is the drawback of it? e.g. Will it harmful to the performance? thanks
解决方案You can create the global variable in android by declaring them in the class which extend the
Application
class.Something like this.
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(); ... } }
Update
This hold the value until your application is not destroyed. If you want to keep your values save even after your application instance destroy then you can use the
SharedPreferences
best way to do this.Learn about the
SharedPrefernces
from here : http://developer.android.com/reference/android/content/SharedPreferences.html这篇关于如何在Android中创建一个全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!