我正在制作一款游戏,我想保存用户的最高分数,所有游戏都在我的游戏中工作,但问题是,当我退出游戏时,自动设置,但我想让它显示给所有用户,直到它休息,然后它会更新。使用sharedpreference保存高分
这是退出游戏后显示对话框:
private void showGameOverDialog() {
int previousScore=getHighScore();
if(playerScore>previousScore){
saveHighScore();
}
//AlertDialog
//AlertDialog.Builder
AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Exit Game");
builder.setMessage("Afraid?");
//Positive, Negative, Neutral
//Anonymous Inner Type Interface Implementation
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
exitGame();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
resetGame();
}
}
);
AlertDialog exitDialog=builder.create();
exitDialog.show();
}
方法来获得高分
private int getHighScore(){
SharedPreferences highScore=getSharedPreferences("high",0);
return highScore.getInt("highScore",0);
}
保存高分
private void saveHighScore(){
SharedPreferences sharedPreferences=getSharedPreferences("data",0);
SharedPreferences.Editor writer=sharedPreferences.edit();
int displayValue=playerScore;
//Username-Highscore
writer.putInt("display",displayValue);
writer.commit();
display();
}
显示了很高的分数
private void display(){
SharedPreferences sharedPreferences=getSharedPreferences("data",0);
String userString=sharedPreferences.getString("playerName","Nothing found");
int highScore=sharedPreferences.getInt("display",0);
username.setText(userString+"-"+highScore);
}
@VishalSharma prefernce文件的名称是“数据”,您在其中保存您的高分,因此检索名称时应该只是“数据”而不是“高”,请尝试上述解决方案,并请知道如果这有效。 –
没有先生,它不工作 –
@VishalSharma现在尝试...你用来保存和检索高分的关键是不同的 –