如何使用共享preferences在Android的存储,读取和编辑值 [英] How to use SharedPreferences in Android to store, fetch and edit values
本文介绍了如何使用共享preferences在Android的存储,读取和编辑值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要存储一个时间值,需要检索和编辑。如何使用共享preferences做到这一点?
I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?
推荐答案
要获得共享preferences,使用下面的方法 在您的活动:
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
要读取preferences:
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
要编辑并保存preferences
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
Android SDK中的样本目录中包含检索和存储共享preferences的一个例子。它坐落在:
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
这篇关于如何使用共享preferences在Android的存储,读取和编辑值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文