为什么共享首选项不保存值?

时间:2015-11-11 21:00:47

标签: java android sharedpreferences

我一直在Android工作室制作应用程序(游戏)并进行测试,但这一切似乎都有效。也就是说,当我获得新的高分时,它要么没有正确保存,要么没有正确显示。

public GamePanel(Context context) {
  super(context);
  this.mContext = context;
}





//display

public void drawText(Canvas canvas) {
    SharedPreferences prefs = mContext.getSharedPreferences("PrefsKeys", Context.MODE_PRIVATE);
    int oldScore = prefs.getInt("highScore", 0);
    int newScore = Player.getScore() * 3;

    //update score only if new score is higher
    if (newScore > oldScore) {
      SharedPreferences.Editor editor = prefs.edit();
      editor.putInt("highScore", 0);
      editor.commit();
    }

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(30);
    paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
    canvas.drawText("DISTANCE: " + newScore, 10, HEIGHT - 10, paint);
    canvas.drawText("HighScore: " + oldScore, WIDTH - 215, HEIGHT - 10, paint);

1 个答案:

答案 0 :(得分:6)

editor.putInt("highScore", 0);

可能意味着

editor.putInt("highScore", newScore);