高分数据持久性?

时间:2015-03-02 14:06:19

标签: java android data-persistence

我正试图为我的比赛保存高分。我有一个主屏幕活动,一个游戏屏幕活动和一个重定向屏幕活动(当玩家输了)。以下是玩家死亡时运行的游戏屏幕活动的方法:

public void goToRedirectScreen()
{
    //getting preferences
    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", this.MODE_PRIVATE);
    int highScore = prefs.getInt("highScore", 0); //0 is the default value

    rectBlack1.setFixedColor(0xFFFF0015);
    rectBlack2.setFixedColor(0xFFFF0015);
    rectBlack3.setFixedColor(0xFFFF0015);
    rectWhite1.setFixedColor(0xFFFF0015);
    rectWhite2.setFixedColor(0xFFFF0015);
    rectWhite3.setFixedColor(0xFFFF0015);

    //Sound when player dies
    MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.deathsound);
    mediaPlayer.start();

    Intent intent = new Intent(this, Redirect.class);

    if (mScoreboard.getScore() > highScore){
        mScoreboard.setHighScore(mScoreboard.getScore());
    }

    intent.putExtra("score", mScoreboard.getScore() + "");
    intent.putExtra("highScore", mScoreboard.getHighScore() + "");
    startActivity(intent);
}

以下是我的重定向屏幕的一些代码,它收到了意图:

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

    Intent intent = getIntent();
    mScore = intent.getStringExtra("score");
    mHighScore = intent.getStringExtra("highScore");

    //**********setting preferences************
    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", this.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("highScore", Integer.parseInt(mHighScore));
    editor.commit();

    ButterKnife.inject(this);

    scoreTextView.setText(mScore);
    highScoreTextView.setText(mHighScore);


    playAgainButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playAgain();

        }
    });

    mainMenuButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            goToMainMenu();
        }
    });



}

要做到这一点,我引用Need to save a high score for an Android game来做这件事,但现在我不知道我做错了什么,因为无论我在测试游戏时得到什么分数,高分和得分textview总是一样的即使它高于我之前的分数。

以下是我的记分板课程,以防它有用:

public class Scoreboard {
private int mScore = 0;
private int mHighScore = 0;

public void addPoint() {
    mScore += 1;
}

public int getHighScore() {
    return mHighScore;
}

public void setHighScore(int highScore) {
    mHighScore = highScore;
}

public int getScore() {
    return mScore;
}

public void setScore(int score) {
    mScore = score;
}

}

1 个答案:

答案 0 :(得分:0)

加载后将加载的值设置为高分:

int highScore = prefs.getInt("highScore", 0); //0 is the default value
mScoreboard.setHighScore(highScore);

否则,如果新分数不是新的高分,则您从未实际使用过加载的值,因此现有的高分不会传递到您的重定向屏幕。