How do I save and modify values using Shared Preferences on Android?

Asked 1 years ago, Updated 1 years ago, 93 views

I'm going to save the time value and get it and edit it How can I do that with Shared Preferences?

android sharedpreferences

2022-09-22 08:33

1 Answers

First, you can create Shared Preferences in the activity method as shown below.

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

Reading preferences.

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

// Receives the current time value as newData().getTime().
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

You can do it like this.

Modify and save preferences

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

Do it like this.

There is an example of storing and receiving preferences in a sample project of Android sdk. The route is <android-sdk-home>/samples/android-<platformversion>/ApiDemos directory This is.

It is also important to distinguish the difference between commit() and apply(). commit() returns true when the value is successfully saved and false when not. commit stores values in Shared Preferences synchronously. apply() was added to version 2.3, but there is no return value. It stores values asynchronously to store them immediately.


2022-09-22 08:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.