Android 相当于 iOS 中的 NSUserDefaults
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3584267/
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
Android equivalent of NSUserDefaults in iOS
提问by christian Muller
I'd like to save some simple data. On the iPhone, I can do it with NSUserDefaults
in Objective-C.
我想保存一些简单的数据。在 iPhone 上,我可以用NSUserDefaults
Objective-C 来完成。
What is the similar command here in Android?
Android 中的类似命令是什么?
I'm just saving a few variables, to be reused as long as the application is installed. I don't want to use a complicated database just to do that.
我只是保存了一些变量,只要安装了应用程序就可以重复使用。我不想使用复杂的数据库来做到这一点。
回答by christian Muller
This is the most simple solution I've found:
这是我找到的最简单的解决方案:
//--Init
int myvar = 12;
//--SAVE Data
SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("var1", myvar);
editor.commit();
//--READ data
myvar = preferences.getInt("var1", 0);
Where 'context' is the current context (e.g. in an activity subclass could be this).
其中“上下文”是当前上下文(例如,在活动子类中可以是this)。