【发布时间】:2018-04-10 17:59:06
【问题描述】:
我正在使用 Android Studio 制作游戏,当我重新加载应用程序时,我用于获得高分的 SharedPreferences 没有被保存。在应用程序中它可以正常工作,但重新启动会将高分发送回默认值 (0)。
设置我在 MainActivity 中的 SharedPreferences:
SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if(currentTopic == 4){
if(settings.getInt("HIGHSCORE", 0) < Math.round(scoreTotal)){
editor.clear();
editor.putInt("HIGHSCORE", Math.round(scoreTotal));
editor.apply();
editor.commit();
}
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
homeIntent.putExtra("Score", Integer.toString(Math.round(scoreTotal)));
startActivity(homeIntent);
editor.commit();
finish();
为了澄清,代码确实进入了 if 语句。 “scoreTotal”是我保存的最高分。
在 HomeActivity 中获取我的 SharedPreferences:
SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highscore = settings.getInt("HIGHSCORE", 0);
Log.i("highscore", String.valueOf(highscore));
TextView tv_highscore = findViewById(R.id.tv_highscore);
tv_highscore.setText("Highscore: "+String.valueOf(highscore));
我哪里出错了?
如果我忘记包含某些内容,请告诉我。我从以前的 StackOverflow 帖子中尝试了很多东西,但无济于事。提前致谢。
编辑:澄清一下,我的问题来自无法在该活动中执行 SharedPreferences 然后从另一个活动中获取它们。我使用了意图额外消息并在 HomeActivity 中执行了所有 SharedPreferences 并且它起作用了。希望这能够帮助一些人。
【问题讨论】:
-
你为什么叫“editor.commit();”在“完成()”之前?如果
if语句失败,您可能不会进行任何编辑。如果没有失败,甚至可以再次调用它 -
您不是已经将分数作为附加项传递给 HomeActivity 了吗?为什么不使用这些数据?此外,第二次 commit() 调用是无用的,就像@Barns 评论的那样
标签: java android android-studio