简体   繁体   English

我如何从共享首选项中读/写高分

[英]How can I read / write a highscore from / to shared preferences

I am writing a game and it needs to record the player's highscore and other info using SharedPrefernces . 我正在编写一个游戏,它需要使用SharedPrefernces记录玩家的高分和其他信息。 Here is my code to record the highscore, in Activity A 这是我在活动A中记录高分的代码

if (score > highcore) {
    highscore = score;
    getPreferences(MODE_PRIVATE).editor().putInt("highscore", score);
}

And then, in Activity BI read the highscore and output it in a TextView . 然后,在Activity BI中读取高分并将其输出到TextView

textView.setText ("Highscore:" + Integer.toString(getPreferences(MODE_PRIVATE).getInt ("highscore", 0)));

However, the output is 0. I thought it is because the two calls to putInt and getInt are in different activities. 但是,输出为0。我认为这是因为对putIntgetInt的两个调用处于不同的活动中。 So I put a breakpoint in one of Activity A's methods and use the "Evaluate Expression" button to evaluate getPreferences(MODE_PRIVATE).getInt ("highscore", 0) but it stills says it's 0. Why? 因此,我在Activity A的方法之一中设置了一个断点,并使用“评估表达式”按钮评估getPreferences(MODE_PRIVATE).getInt ("highscore", 0)但仍然说是0。为什么?

I think this has something to do with MODE_PRIVATE ? 我认为这与MODE_PRIVATE If I cannot use MODE_PRIVATE , what can I use? 如果我不能使用MODE_PRIVATE ,我可以用什么?

You forgot to commit: 您忘记提交:

    getPreferences(MODE_PRIVATE).editor().putInt("highscore", score).commit();

In addition, as docs say about getPreferences(MODE_PRIVATE): 此外,正如文档中关于getPreferences(MODE_PRIVATE)所说的那样:

This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name. 通过传入此活动的类名称作为首选项名称,可以简单地调用基础的getSharedPreferences(String,int)方法。

So you read another Prefernce file in Activity B. 因此,您在活动B中读取了另一个首选项文件。

instead you can use: 相反,您可以使用:

  PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("highscore", score).commit();

And read it back in Activity B: 并在活动B中重新阅读:

PreferenceManager.getDefaultSharedPreferences(this).getInt("highscore", score);

All changes you make in an editor are batched , and not copied back to the original SharedPreferences until you call commit() or apply() . 您在编辑器中进行的所有更改都将被批量处理 ,并且直到您调用commit()apply()时才将其复制回原始的SharedPreferences

You can use: 您可以使用:

PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("highscore", score).commit();

Actually commit() writes its preferences out to persistent storage synchronously. 实际上commit()会将其首选项同步写入持久性存储。

you need to add editor.commit(); 您需要添加editor.commit(); or editor.apply(); editor.apply(); when storing the data to preferences.. 将数据存储到首选项时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM