Updating Shared Preferences to Include Game State Settings

To keep track of game state, you need to add two more Integer settings to the application SharedPreferences: the game score and the current question number. To add these preferences, you first declare the preference name String values to the QuizActivity.java class:

public static final String GAME_PREFERENCES_SCORE = "Score";

public static final String GAME_PREFERENCES_CURRENT_QUESTION = "CurQuestion";

Next, you define the SharedPreferences object as a member variable of the QuizGameActivity class: SharedPreferences mGameSettings;

You initialize the mGameSettings member variable in the onCreate() method of the QuizGameActivity class:

mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);

Now you can use SharedPreferences throughout the class, as needed, to read and write game settings such as the current question and the game score. For example, you could get the current question by using the getInt() method of SharedPreferences as follows:

int startingQuestionNumber =


0 0

Post a comment