alexward1230
alexward1230

Reputation: 589

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);

Upvotes: 1

Views: 2303

Answers (2)

Pavandroid
Pavandroid

Reputation: 1586

Just before Saving the high score, Fetch the current high score which is saved in the preferences and check whether it is less than the highscore or not. if it is less then save the new one in to Shared preferences or else just leave the past one as highest.

Upvotes: 2

Chirag Patel
Chirag Patel

Reputation: 11508

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

Upvotes: 3

Related Questions