Creating And Saving Shared Preferences in Android

Using the SharedPreferences class, you can create named maps of name/value pairs that can be persisted across sessions and shared among application components running within the same application sandbox.

To create or modify a Shared Preference, call getSharedPreferences on the current Context, passing in the name of the Shared Preference to change.

SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, 
 Activity.MODE_PRIVATE);

Shared Preferences are stored within the application’s sandbox, so they can be shared between an application’s components but aren’t available to other applications.

To modify a Shared Preference, use the SharedPreferences.Editor class. Get the Editor object by calling edit on the Shared Preferences object you want to change.

SharedPreferences.Editor editor = mySharedPreferences.edit();
Use the put<type> methods to insert or update the values associated with the specified name:
// Store new primitive types in the shared preferences object.
editor.putBoolean(“isTrue”, true);
editor.putFloat(“lastFloat”, 1f);
editor.putInt(“wholeNumber”, 2);
editor.putLong(“aNumber”, 3l);
editor.putString(“textEntryValue”, “Not Empty”);

To save edits, call apply or commit on the Editor object to save the changes asynchronously or synchronously, respectively.

// Commit the changes.
editor.apply();

Leave a Comment