Android 退出应用程序后保存变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11688689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
save variables after quitting application?
提问by Stupe
I want some variables to be saved, when I shut down my app and to load them after opening the app (for statistics in a game)
我想要一些变量被保存,当我关闭我的应用程序并在打开应用程序后加载它们(用于游戏中的统计)
How can I do this?
我怎样才能做到这一点?
EDIT: Here my code:
编辑:这是我的代码:
TextView test1;
String punkte = "15";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("score", punkte);
SharedPreferences load = getSharedPreferences(punkte, 0);
String points = load.getString("score", "0");
test1 = (TextView) findViewById(R.id.test1);
test1.setText(points);
}
回答by Mxyk
You should be using SharedPrefences
. They are quite simple to use and will store the variables in the application data. As long as the user never hits "Clear Data" in the settings for your application, they will always be there.
你应该使用SharedPrefences
. 它们使用起来非常简单,并将变量存储在应用程序数据中。只要用户从未在您的应用程序设置中点击“清除数据”,他们就会一直在那里。
Here is a code sample.
这是一个代码示例。
To access variables:
访问变量:
SharedPreferences mPrefs = getSharedPreferences("label", 0);
String mString = mPrefs.getString("tag", "default_value_if_variable_not_found");
To edit the variables and commit (store) them:
要编辑变量并提交(存储)它们:
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("tag", value_of_variable).commit();
Make sure both "tag" fields match!
确保两个“标签”字段匹配!
回答by MAC
回答by enjoy-writing
sample code: save:
示例代码: 保存:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString("statepara1", ts);
editor.commit();
get:
得到:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
String ret = settings.getString("statepara1", "0");