2012-03-17 76 views
1

所以我試圖用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); 
+0

順便說一句,這是一個遊戲,我試圖只保存#1的最高分,這只是一個整數。再次感謝任何幫助。 – alexward1230 2012-03-17 04:10:44

回答

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

我希望這會幫助你。

2

就在保存高分之前,獲取保存在首選項中的當前高分並檢查它是否爲樂ss高於或低於高分。如果它較少,則將新的保存到「共享」偏好設置中,否則將過去的保留爲最高。