Search code examples
androidsharedpreferencessaving-data

Show the highscore with shared preferences?


So I'm trying to save the highest score with sharedPreferences but I am running into trouble. I don't know how I would set it up to only take the highest score and display it.

What I have now will only display the current score that the player recieves. Here is what I have so far that doesnt work:

public class GameOptions extends Activity {
int theScore;
TextView highScore;
public static String filename = "MyHighScore";
SharedPreferences spHighScore;
int dataReturned;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.in_game_menu);
    TextView tvTheScore = (TextView) findViewById(R.id.textView2);
    TextView highScore = (TextView) findViewById(R.id.high_score);
    Bundle gotScore = getIntent().getExtras();
    theScore = gotScore.getInt("scoreKey"); 
    //String thisIsTheScoreToDisplay = theScore.toString();
    tvTheScore.setText("SCORE: "+theScore);

    spHighScore = getSharedPreferences(filename, 0);
    SharedPreferences.Editor editor = spHighScore.edit();

    editor.putInt("highScoreKey", theScore);
    editor.commit();

    int dataReturned = spHighScore.getInt("highScoreKey", 0);
    highScore.setText("" + dataReturned);

Solution

  • by this you can save your score

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
        prefsEditor.putString(MY_SCORE_KEY, HIGHEST_SCORE);
        prefsEditor.commit();
    

    and get like this

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        String highestScore = myPrefs.getString(MY_SCORE_KEY, "nothing");
    

    I hope this will help you..