【问题标题】:Highscore isn't being saved高分未保存
【发布时间】:2016-10-20 02:56:17
【问题描述】:

我尝试使用这个问题的答案Need to save a high score for an Android game 来保存一个简单的 int, score,但我遇到了麻烦。从我的游戏活动中,我传递了一个名为 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);
}

【问题讨论】:

  • 您尝试过什么来保存分数?问题出在哪里? (基本上有三种方法可以在您的应用程序中存储数据:a)sharedPreferences b)files c)databse)如果您知道您想要哪种方法,请告诉我如何为您提供帮助! (查看 sharedPreferences!)
  • 我尝试使用 sharedPreferences,它位于第一个名为“丢失屏幕”的块中。这是这一部分: SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); int highScore = prefs.getInt("highScore", 0); //0 是默认值 if (newScore > highScore) { prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); SharedPreferences.Editor 编辑器 = prefs.edit(); editor.putInt("highScore", newScore); editor.commit(); highScore = newScore; }
  • 这里的评论很难读懂,但在第一个块中大约有 20 行,从 Shared Preferences prefs = 开始
  • 嗯对,我没看到!对不起,我的错!
  • 没关系,很容易错过。你能告诉我我做错了什么吗?我确定这是一个简单的错误,但我是一个 android 菜鸟,不知道为什么它不能正确保存高分

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


【解决方案1】:

所以这很奇怪,但在不更改代码的情况下它现在正在工作。发布此问题后,我的 android 工作室开始行动;我遇到了无法解析符号“r”的错误,不得不重建和清理我的项目。几次重新启动后,我注意到现在也可以正确保存高分。很奇怪。

【讨论】:

  • 好吧 - 没那么糟糕...这样比它仍然无法运行要好 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多