Developer
Developer

Reputation: 49

Android Save High Scores

What's up guys I'm developing a game for Android and I have one problem that I didn't find in internet.I want to save the high score with shared preferences and that is the code:

Play Class : 
        SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
        Editor edit = prefs.edit();
        edit.putInt("key", score);
        edit.commit();
        Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_LONG).show();

        Intent it = new Intent(getApplicationContext(),HighScore.class);
        startActivity(it);

And this is the high score list code :

highscore = (TextView) findViewById(R.id.highscore_int);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", 
                                                    Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
highscore.setText(""+score);

This works fine but it saves all scores even it's smaller than previous. I want to save the score only if it's bigger than previous. How can I do that? PS : Sorry for my English and I don't know how to highlight the code :(

Upvotes: 0

Views: 4773

Answers (1)

Care_Today
Care_Today

Reputation: 96

SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int oldScore = prefs.getInt("key", 0);  
if(newScore > oldScore ){
   Editor edit = prefs.edit();
   edit.putInt("key", newScore);
   edit.commit();
}

to see.

Upvotes: 8

Related Questions