Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
From the author of

Storing and Updating Shared Preferences

Storing values is similar to retrieving application preferences, but you must first get an instance of the SharedPreferences.Editor object (android.content.SharedPreferences.Editor). All changes to the preferences are performed using the Editor object, and then committed together. Do this by calling the edit() method of the SharedPreferences object, like so:

Editor settingsEditor = settings.edit();

Now you are free to add or update preference values, based on their key names. Use the setter methods, such as putBoolean(), putFloat(), putInt(), and putString() to store values retrievable by their key names. After all changes have been made, you must call the commit() method (or the asynchronous apply() method, for API Level 9+) of the Editor to actually write the changes to the preference file. You can remove specific preference values by name using the remove() method or remove all preferences in a given group with the clear() method. These operations must still be committed before they will apply.

The following demonstrates the storing and committing of several preference values:

settingsEditor.putBoolean("some_flag", true);
settingsEditor.putString("some_string", "new value");
settingsEditor.commit();

That's all there is to storing and retrieving preferences within your application persistently.

  • + Share This
  • 🔖 Save To Your Account