質問

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);
役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top