Reputation: 149
I am trying to make it possible that you can save a high score and I also need the user to be able to reset/delete their high score. the TOAST works but the data doesn't get deleted.
public static final String PREFS_NAME = "MyPrefsFile";
static SharedPreferences settings;
static SharedPreferences.Editor editor;
// When 'back' button is pressed save the highscore to settings
editor = settings.edit();// Create a new editor
editor.putInt("highscore", HighScore); // Storing integer
editor.commit();
// When 'Show' button is pressed
public void showPreferences(View v) {
int highscore = GameActivity.settings.getInt("highscore", GameActivity.HighScore);
Toast.makeText( MainMenu.this, "Your Highscore is: " + highscore, Toast.LENGTH_LONG).show();
}
//When delete button is pressed
public void clearPreferences(View V) {
GameActivity.editor = GameActivity.settings.edit();// Create a new editor
GameActivity.editor.clear();
GameActivity.editor.commit();
Toast.makeText( MainMenu.this,"Highscore has been reset",Toast.LENGTH_LONG).show();
}
Upvotes: 3
Views: 283
Reputation: 15668
I believe you are just reading it wrong, use this
int highscore = GameActivity.settings.getInt("highscore", 0);
Note that second parameter is the default value, a value that is returned if the value by that key is not present in the settings.
Upvotes: 1
Reputation: 1154
Use the below to clear shared preferences
settings.edit().clear().commit();
Or use the below to clear single value from preferences
settings.edit().remove("highscore").commit();
Upvotes: 0
Reputation: 7065
You can try this:
settings = getSharedPreferences("MyPrefsFile", 0);
preferences.edit().remove("highscore").commit();
Or you can update the sharepreference by the value 0.
Upvotes: 0