无法使用共享偏好保存游戏的高分?

时间:2014-05-18 18:11:58

标签: java android sharedpreferences

这是我用来保存高分的游戏代码

SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    //Highscore.easyHigh = 0;

    Highscore.easyHigh = preferences.getInt("EasyScore", 0);
    Highscore.mediumHigh = preferences.getInt("MediumScore", 0);
    Highscore.hardHigh = preferences.getInt("HardScore", 0);

现在我在玩家失去游戏时设置这些值

editor = preferences.edit();
        if(level==1)
        editor.putInt("EasyScore", score);
        else if(level==2)
        editor.putInt("MediumScore", score);
        else if(level==3)
        editor.putInt("HardScore", score);
        editor.commit();

Highscore是我的类,存储公共静态int easy,medium,hard?

我得到一个空指针异常,但为什么会这样呢?

2 个答案:

答案 0 :(得分:2)

您的偏好设置和编辑器值未初始化,请使用:

preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();

答案 1 :(得分:0)

您尚未初始化preferenceseditor ..请在代码中setContentView()后执行此操作..

这样做..

preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();