android - 如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值

标签 android sharedpreferences

我想存储一个时间值,需要检索和编辑它。如何使用 SharedPreferences 来做到这一点?

最佳答案

要获取共享首选项,请使用以下方法 在您的 Activity 中:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

阅读偏好:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

编辑和保存首选项

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

android sdk 的示例目录包含一个检索和存储共享首选项的示例。它位于:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

编辑==>

我注意到了,在这里写下 commit()apply() 之间的区别也很重要。

commit() 如果值保存成功则返回 true,否则返回 false。它同步将值保存到 SharedPreferences。

apply() 是在 2.3 中添加的,无论成功还是失败都不返回任何值。它会立即将值保存到 SharedPreferences,但会启动 asynchronous 提交。 更多细节是here .

关于android - 如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3624280/

相关文章:

android - 如何运行单个 android 仪器测试用例?

android - 布局充气器中 "attach to root"有什么用?

c# - AES 解密给出错误的结果

android - fragment 中的共享首选项

android - Dagger 2 - 构造函数注入(inject) - 非 Activity

java - 在 Android 中管理多个 EditText

安卓 : selectors for custom listviews

java - 根据单击的按钮将变量保存在 SharedPreferences 中

java - 为什么我的共享首选项即使在全新安装后仍包含我的 key ?

android - SharedPreference 未按预期工作