这是我用来保存高分的游戏代码
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?
我得到一个空指针异常,但为什么会这样呢?
答案 0 :(得分:2)
您的偏好设置和编辑器值未初始化,请使用:
preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();
答案 1 :(得分:0)
您尚未初始化preferences
和editor
..请在代码中setContentView()
后执行此操作..
这样做..
preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();