Creating Application Preferences

The Been There, Done That! trivia game needs a simple way to store some basic state information and user data. You can use Android's shared preferences (android.content.SharedPreferences) to add this functionality.

You can access shared preferences, by name, from any activity within the application. Therefore, declare the name of your set of preferences in the base class QuizActivity so that they are easily accessible to all subclasses: public static final String GAME_PREFERENCES = "GamePrefs";

Did you Know?

There is no limit to the number of sets of shared preferences you can create. You can use the preference name string to divide preferences into categories, such as game preferences and user preferences. How you organize shared preferences is up to you.

To add shared preferences to the application, take the following steps:

1. Use the getSharedPreferences() method to retrieve an instance of a SharedPreferences object.

2. Create a SharedPreferences.Editor object to modify preferences.

3. Make changes to the preferences by using the editor.

4. Commit the changes by using the commit() method in the editor.

Saving Specific Shared Preferences

Each preference is stored as a key/value pair. Preference values can be the following types:

Long String

After you have decided what preferences you want to save, you need to get an instance of the SharedPreferences object and use the Editor object to make the changes and commit them. In the following example, you save two preferences—the user's name and age:

import android.content.SharedPreferences; // ...

SharedPreferences settings =

getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE); SharedPreferences.Editor prefEditor = settings.edit(); prefEditor.putString("UserName", "JaneDoe"); prefEditor.putInt("UserAge", 22); prefEditor.commit();

You can also use the shared preferences editor to clear all preferences, using the clear() method, and to remove specific preferences by name, using the remove() method.

Retrieving Shared Preferences

Retrieving shared preference values is even simpler than creating them because you don't need an editor. The following example shows how to retrieve shared preference values:

SharedPreferences settings =

getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE); if (settings.contains("UserName") == true) { // We have a user name

String user = Settings.getString("UserName", "Default");

You can use the SharedPreferences object to check for a preference by name, retrieve strongly typed preferences, or retrieve all the preferences and store them in a map.

Although you have no immediate needs for shared preferences yet in Been There, Done That! you now have the infrastructure set up to use them as you need them within all the application activities. This will be handy when you begin to implement each activity later in the book.

0 0

Post a comment