17

It's quite simple, all I need to do is save a high score (an integer) for the game. I'm assuming the easiest way to do this would be to store it in a text file but I really have no idea how to go about doing this.

aelsheikh
  • 2,268
  • 5
  • 26
  • 41

4 Answers4

41

If all you need is to store an integer then SharedPreferences would be best for you to use:

//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();

To get a preference:

//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value

Of course replace "key" with the key for your high score value and "myPrefsKey" with the key for your preferences (These can be whatever. It's just good to set them to something recognizable and unique).

dymmeh
  • 22,247
  • 5
  • 53
  • 60
  • 1
    Just to confirm, will this store the data so the next time I run the game I can sill get it? – aelsheikh Dec 06 '11 at 21:55
  • 2
    Yes, this data persists between runs of your app. Just make sure to call commit(); on the editor for them to be saved! – dymmeh Dec 06 '11 at 21:56
  • that "myPrefsKey" have to be unique only for my app or global? – Michal Apr 23 '13 at 16:05
  • @MichalChovanec - You only need to make the name unique for your app. – dymmeh Apr 23 '13 at 20:05
  • @dymmeh Do I have to re make the SharedPreferences object? I get 'variable prefs is already defined in the scope' – Ruchir Baronia Nov 05 '15 at 04:05
  • @Rich - No. Those 2 statements would typically be in separate blocks of code. I'll edit my answer to split them up better – dymmeh Nov 05 '15 at 17:04
  • 1
    So, I would name 'myPrefsKey' to 'SampleGameIMade' and 'key' to 'highScore', correct? – so5user5 Feb 25 '16 at 03:51
  • @dymmeh Thanks! And I'm assuming Editor is replaced with SharedPreferences.Editor – so5user5 Feb 25 '16 at 04:16
  • @ideaman924 Yeah. I had SharedPreferences.Editor imported since this was back in the Eclipse days so just Editor is the same thing. – dymmeh Feb 25 '16 at 04:40
  • @dymmeh: I `putInt` on a.kt and `getInt` on b.kt on a same project and this didn't work. My project contains 2 activities a.kt and b.kt. – Steven Lee Apr 05 '23 at 23:39
  • @StevenLee can you share your code – dymmeh Apr 07 '23 at 00:29
  • b.kt `override fun onCreate(savedInstanceState: Bundle?) { ... //getting preferences val prefs = getSharedPreferences("myHighScore", Context.MODE_PRIVATE) val totalScore = prefs.getInt("keytotalScore", 0) //0 is the default value }` a.kt `override fun onCreate(savedInstanceState: Bundle?) { ... //setting preferences val prefs = getSharedPreferences("myHighScore", Context.MODE_PRIVATE) val editor: SharedPreferences.Editor = prefs.edit() editor.putInt("keytotalScore", totalScore) editor.commit() }` – Steven Lee Apr 07 '23 at 04:36
2

Use shared preferences:

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}

It's easiest way to store such a things.

vallentin
  • 23,478
  • 6
  • 59
  • 81
Costa Mirkin
  • 947
  • 3
  • 15
  • 39
2

I think this link will help you in it:

The SharedPreferences class provides a general framework that allows you to save and
retrieve persistent key-value pairs of primitive data types. You can use
SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. 
This data will persist across user sessions (even if your application is killed).

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone
a user has chosen. If you're interested in creating user preferences for your
application, see PreferenceActivity, which provides an Activity framework for you to 
create user preferences, which will be automatically persisted (using shared preferences).

To get a SharedPreferences object for your application, use one of two methods:

    getSharedPreferences() - Use this if you need multiple preferences files identified
by name, which you specify with the first parameter.
    getPreferences() - Use this if you need only one preferences file for your Activity.
Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

    Call edit() to get a SharedPreferences.Editor.
    Add values with methods such as putBoolean() and putString().
    Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

As I see, the best way for you to save high score is SharedPreferences.

030
  • 10,842
  • 12
  • 78
  • 123
Belurd
  • 772
  • 1
  • 13
  • 31
0
public class HighScores extends Activity {

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

        //get text view
        TextView scoreView = (TextView)findViewById(R.id.high_scores_list);
        //get shared prefs
        SharedPreferences scorePrefs = getSharedPreferences(PlayGame.GAME_PREFS, 0);
        //get scores
        String[] savedScores = scorePrefs.getString("highScores", "").split("\\|");
        //build string
        StringBuilder scoreBuild = new StringBuilder("");
        for(String score : savedScores){
            scoreBuild.append(score+"\n");
        }
        //display scores
        scoreView.setText(scoreBuild.toString());
    }

}
Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
Ritesh
  • 1