显示共享偏好的高分?

时间:2012-03-17 04:04:21

标签: android sharedpreferences saving-data

所以我试图用sharedPreferences保存最高分,但我遇到了麻烦。我不知道如何将其设置为仅获得最高分并显示它。

我现在拥有的只会显示玩家收到的当前分数。到目前为止,这是我的工作:

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

2 个答案:

答案 0 :(得分:3)

通过这个你可以保存你的分数

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

并得到这样的

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

我希望这会对你有帮助..

答案 1 :(得分:2)

在保存高分之前,获取保存在首选项中的当前高分并检查它是否小于高分。如果它少了,那么将新的保存到共享首选项中,否则只保留过去的那个。