private void setHighScore(){
SharedPreferences.Editor scoreEdit = gamePrefs.edit();
DateFormat dateForm = new SimpleDateFormat("MM/dd/yy");
String dateOutput = dateForm.format(new Date());
String scores = gamePrefs.getString("highScores", "");
if(scores.length() > 0) {
List<Score> scoreStrings = new ArrayList<Score>();
String[] exScores = scores.split("\\|");
for(String eSc : exScores){
String[] parts = eSc.split(" - ");
scoreStrings.add(new Score(parts[0], Integer.parseInt(parts[1])));
}
Score newScore = new Score(dateOutput, score);
scoreStrings.add(newScore);
Collections.sort(scoreStrings);
StringBuilder scoreBuild = new StringBuilder("");
for (int x = 0; x < scoreStrings.size(); x++){
if(x >= 10) break;
if(x > 0) scoreBuild.append("|");
scoreBuild.append(scoreStrings.get(x).getScoreText());
}
scoreEdit.putString("highScores", scoreBuild.toString());
scoreEdit.commit();
}else{
scoreEdit.putString("highScores", ""+dateOutput+ " - " + score);
scoreEdit.commit();
}
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture,long countDownInterval){
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Times Up!");
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
setHighScore();
Intent intent = new Intent(getApplicationContext(), score_screen.class);
startActivity(intent);
finish();
}
@Override
public void onTick(long millisUntilFinished){
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Left: " + millisUntilFinished/1000);
}
}
public class score_screen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score_screen);
TextView scoreView = (TextView)findViewById(R.id.scoreView);
ImageButton home = (ImageButton)findViewById(R.id.home);
SharedPreferences scorePrefs = getSharedPreferences(Game.GAME_PREFS, 0);
String[] savedScores = scorePrefs.getString("highScores", "").split("\\|");
StringBuilder scoreBuild = new StringBuilder("");
for(String score : savedScores) {
scoreBuild.append(score+"\n");
}
scoreView.setText(scoreBuild.toString());
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ColorMatch.class);
startActivity(intent);
}
});
}
}
我想在計時器啓動後從我的遊戲屏幕保存高分。我能夠做到這一點很好,然後當我第二次訪問我的ArrayList時,最後得分被重新保存,我不知道爲什麼會發生這種情況。SharedPreferences兩次保存數據
例如,一場比賽結束後得分爲3170,它將我帶到高分屏幕,我只看到一個得分實例。然後,如果我玩一個新遊戲,或從主菜單打開我的高分榜屏幕,我現在可以看到兩個相同分數的實例。 (3170)我的猜測是雙擊了分數,但在高分屏幕中我找不到第二個.commit()。
調試它,你可能會發現問題。也許你打電話給setHighscore兩次。 –
我已經使用搜索功能檢查了這一點。我相信這是一個數據問題的原因是因爲它在遊戲結束並打開score_screen活動後立即行動。第二次得分只會在score_screen第二次打開後出現。 –
也許你保留的片段再次發送相同的數據。 –