2012-03-17 54 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高于或低于高分。如果它较少,则将新的保存到“共享”偏好设置中,否则将过去的保留为最高。