Android 相当于 iOS 中的 NSUserDefaults

发布于 2024-09-16 06:13:12 字数 279 浏览 2 评论 0原文

我想保存一些简单的数据。在 iPhone 上,我可以使用 NSUserDefaults

Android 中类似的命令是什么?

我只是保存一些变量,只要安装了应用程序就可以重复使用。我不想使用复杂的数据库来做到这一点。

I'd like to save some simple data. On the iPhone, I can do it with NSUserDefaults in Objective-C.

What is the similar command here in 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

于我来说 2024-09-23 06:13:12

这是我发现的最简单的解决方案:

//--Init
int myvar = 12;


//--SAVE Data
SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);  
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("var1", myvar);
editor.apply();


//--READ data       
myvar = preferences.getInt("var1", 0);  

其中“context”是当前上下文(例如,在活动子类中可以是this)。

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.apply();


//--READ data       
myvar = preferences.getInt("var1", 0);  

Where 'context' is the current context (e.g. in an activity subclass could be this).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文