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

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是我的课程将public static int存储为easy,medium,hard吗?

我得到一个空指针异常,但是为什么会发生呢?

最佳答案

您的首选项和编辑器值未初始化,请使用以下命令:

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

关于java - 无法使用共享的首选项保存游戏的高分?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23725268/

10-11 13:29