我想存储一个时间值,需要检索和编辑它。如何使用 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/