如何使用共享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