高分未被保存

时间:2016-10-20 02:56:17

标签: java android android-layout android-studio sharedpreferences

我尝试使用此问题的答案Need to save a high score for an Android game来保存简单的int,得分,但我遇到了麻烦。从我的游戏活动中,我传递了一个名为newScore的int,并将其放入我的丢失屏幕活动中。我检查newScore> highScore,如果是这样,我将newScore作为新的高分。我也展示了两者。目前,它始终在屏幕上显示高分和得分相同。因此,即使我得分为10分,下次如果我回来并得分1,它将显示1为高分。

这是我尝试访问高分的代码,如果它更大则输入新分数

来自

public class LoseScreen extends AppCompatActivity`:

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

    Bundle b = getIntent().getExtras();
    int newScore = b.getInt("newScore");

    TextView textView6 = (TextView) findViewById(R.id.textView6);
    textView6.setText("Score: " + newScore);

    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    int highScore = prefs.getInt("highScore", 0); //0 is the default value

    if (newScore > highScore) {
        prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("highScore", newScore);
        editor.commit();
        highScore = newScore;
    }

    TextView textView8 = (TextView) findViewById(R.id.textView8);
    textView8.setText("High Score: " + highScore);
}

我还会从我的主要游戏活动中放入我的退出方法;我没有为我的班级发布整个代码,因为我觉得它相当大而且无关紧要。如果它有帮助,我会很乐意发布它。

 public void quit() {
    Intent intent = new Intent(ColorMatch2.this,
            LoseScreen.class);
    int newScore = score;
    Bundle b = new Bundle();
    b.putInt("newScore", newScore); // Your score
    intent.putExtras(b); // Put your score to your next
    startActivity(intent);
}

1 个答案:

答案 0 :(得分:0)

所以这很奇怪,但是如果不改变代码,它现在正在工作。在发布这个问题后,我的android工作室开始表现;我有一个无法解决的符号' r'错误,不得不重建和清理我的项目。几次重启后,我注意到现在也正确地保存了高分。怪异。

相关问题