Reading Settings from Shared Preferences

When you begin saving settings in a persistent fashion, you are going to need to be able to read them back out and load them into the form (for editing). To do this, you need to access the game preferences and check whether specific settings exist. For example, you might want to check and see if the Nickname setting is set, and if so, load its value into the EditText input field called EditText_Nickname. You can do this by using the contains() and getString() methods of SharedPreferences:

final EditText nicknameText =

(EditText) findViewById(; if (mGameSettings,contains(GAME_PREFERENCES_NICKNAME)) { nicknameText.setText(mGameSettings.getString( GAME_PREFERENCES_NICKNAME, "" ));

Here, you check for the existence of a specific setting name defined as GAME_PREFER-ENCES_NICKNAME in SharedPreferences by using the contains() method. If the contains() method returns true, you extract the value of that setting (a String setting) from SharedPreferences by using the getString() method.

The Nickname, Email, and Password settings are strings and can be extracted using the getString() method. However, the Date of Birth setting must be extracted using the getLong() method, and the Gender setting requires the getInt() method.

Did you Know?

Finally, for testing purposes, you override the onDestroy() method of QuizSettingsActivity to log all current settings whenever the settings screen is destroyed: ©Override protected void onDestroy() {

Log.d(DEBUG_TAG, "SHARED PREFERENCES"); Log.d(DEBUG_TAG, "Nickname is: "

+ mGameSettings,getString(GAME_PREFERENCES_NICKNAME, "Not set")); Log.d(DEBUG_TAG, "Email is: "

+ mGameSettings,getString(GAME_PREFERENCES_EMAIL, "Not set")); Log.d(DEBUG_TAG, "Gender (M=1, F=2, U=0) is: "

+ mGameSettings,getInt(GAME_PREFERENCES_GENDER, 0)); // We are not saving the password yet Log.d(DEBUG_TAG, "Password is: "

+ mGameSettings,getString(GAME_PREFERENCES_PASSWORD, "Not set")); // We are not saving the date of birth yet Log.d(DEBUG_TAG, "DOB is: "

+ DateFormat.format("MMMM dd, yyyy", mGameSettings.getLong(

Application preferences are stored on the Android file system as XML files. Preferences files can be accessed using the File Explorer of the Eclipse DDMS perspective. SharedPreferences files are found in the following directory: /data/data/<package name>/shared_prefs/<preferences filename>.xml

GAME_PREFERENCES_DOB, 0))); super.onDestroy();

Now whenever QuizSettingsActivity is destroyed (for example, when a user presses the Back button), the preferences that have been committed are displayed in the LogCat console.

0 0

Post a comment