如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值 [英] How to use SharedPreferences in Android to store, fetch and edit values
问题描述
我想存储一个时间值,需要检索和编辑它.我如何使用 SharedPreferences
来做到这一点?
I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences
to do this?
推荐答案
要获取共享首选项,请使用以下方法在您的活动中:
To obtain shared preferences, use the following method In your 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 的示例目录包含检索和存储共享首选项的示例.它位于:
The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
编辑==>
我注意到,在这里写下 commit()
和 apply()
之间的区别也很重要.
I noticed, it is important to write difference between commit()
and apply()
here as well.
commit()
如果值保存成功则返回 true
否则返回 false
.它将值同步保存到 SharedPreferences.
commit()
return true
if value saved successfully otherwise false
. It save values to SharedPreferences synchronously.
apply()
是在 2.3 中添加的,无论成功还是失败都不会返回任何值.它会立即将值保存到 SharedPreferences,但会启动一个异步提交.更多细节在这里.
这篇关于如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!