简体   繁体   中英

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 . Here is my code to record the highscore, in Activity 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 .

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. 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?

I think this has something to do with MODE_PRIVATE ? If I cannot use MODE_PRIVATE , what can I use?

You forgot to commit:

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

In addition, as docs say about getPreferences(MODE_PRIVATE):

This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

So you read another Prefernce file in Activity B.

instead you can use:

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

And read it back in Activity 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() .

You can use:

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

Actually commit() writes its preferences out to persistent storage synchronously.

you need to add editor.commit(); or editor.apply(); when storing the data to preferences..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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