Loading and Saving Persistent Preferences

Introduction
In this tutorial, you will learn how to save variables to persistent preferences and how to load them on other instances. You won't need to work with the filesystem, as Android can manage saved variables by itself.

Dependencies
No special dependencies are needed for this tutorial.

Importing
Import the following classes:

Initializing the SharedPreferences and Editor
You can start up a SharedPreference inside a method, or create a reuseable one. Declare a SharedPreferences variable:

Initialize the variable by calling the method getDefaultSharedPreferences from a PreferenceManager.

Declare an Editor variable:

Saving a preference
For saving or loading preferences, android searches for values using String keys. Setup a string that will name our preference. In this tutorial, we will call it PREFERENCE_TUTORIAL.

Setup the Editor to edit the preferences with the edit method.

Now you will input whichever values you like. Android differentiates some kinds of variables, so you won't have to go through the trouble of parsing Strings. Below are listed some of the supported methods:

For this tutorial, we will store an Integer called preferenceInt.

You can save more variables at the same time. When you are finished, you have two methods to save changes. The first one is commit, that will run in the main thread, and the last one is apply, that will run asynchronously in the background.

If it will not affect other methods of your application, always choose to run in the background. But if you need it to save instantly, you should choose commit.

When you are finished, your code should look like this:

Loading a Preference
After you saved the preference keys, you can load them whenever you want, even after you close your application. Put methods for loading preferences in the onCreate method to keep inputed data persistent through instances.

To load a preference, redeclare the key you want.

Now you can use the SharedPreferences to get the values saved. You can use methods that are similar to the ones commented in the previous section. The first parameter is the String key. The second parameter is a default value, in case it doesn't find our key. This is useful for first runs or when the value is corrupted.

When you are finished, your code should look like this:

Conclusion
Your application can now load and save any preferences. This doesn't replace the use of a PreferenceSettings activity.

You now know how to save variables to the preferences and how to load them anytime.