清除共享首选项

时间:2015-05-06 20:45:45

标签: java android sharedpreferences

我试图让你可以保存高分,我还需要用户能够重置/删除他们的高分。 TOAST有效,但数据不会被删除。

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();
    }

3 个答案:

答案 0 :(得分:1)

我相信你只是读错了,用这个

int highscore = GameActivity.settings.getInt("highscore", 0);

请注意,第二个参数是默认值,如果设置中不存在该键的值,则返回该值。

答案 1 :(得分:0)

你可以试试这个:

settings = getSharedPreferences("MyPrefsFile", 0);
preferences.edit().remove("highscore").commit();

或者您可以按值0更新共享偏好。

答案 2 :(得分:0)

使用以下内容清除共享偏好

settings.edit().clear().commit();

或使用以下内容清除首选项中的单个值

settings.edit().remove("highscore").commit();