TheKaiser4
TheKaiser4

Reputation: 149

Clear Shared Preferences

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

Answers (3)

Bojan Kseneman
Bojan Kseneman

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

Iqbal S
Iqbal S

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

Mohammad Arman
Mohammad Arman

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

Related Questions