我对Android很新,习惯于iOS。共享偏好有点困难。我基本上首次在我的设置视图中初始化,高分为0.
现在在另一个游戏视图中,当我尝试检索此分数并将其与当前分数进行比较以更新它时,它会崩溃。一旦它尝试阅读它,应用程序崩溃。
这是在设置页面中初始化:
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
// similar to view did appear
System.out.println("Settings viewdidappear");
super.onWindowFocusChanged(hasFocus);
int firstTime = 10;
SharedPreferences preferences = this.getSharedPreferences("Settings", Context.MODE_PRIVATE);
int getVar = preferences.getInt("CheckVar", 0);
// set the value first time if not existing already
if (getVar != 10) {
System.out.println("Settings not existant: " + getVar);
SharedPreferences.Editor editor = preferences.edit();
getVar = 10;
editor.putInt("CheckVar", getVar);
editor.putInt("HighScore", 0);
editor.commit();
// add loading for save score
} else {
System.out.println("Settings Already Exists: " + getVar);
}
}
这是在游戏页面中:
public class GameLogic extends View {
SharedPreferences settings;
public void save(Context context) {
System.out.println("Running save");
settings = context.getSharedPreferences("Settings", Context.MODE_PRIVATE);
int getVar = settings.getInt("HighScore", 0);
if (getVar > total_score) {
System.out.println("Putting new value " + total_score);
SharedPreferences.Editor editor = settings.edit();
getVar = total_score;
editor.putInt("HighScore", getVar);
editor.commit();
} else {
System.out.println("Previous score is higher " + getVar);
}
}
public void DidILose() {
score();
if (TappedMine == 2) {
save(null);
flag_for_loss = 1;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getContext());
alertDialogBuilder.setTitle("Game Over");
alertDialogBuilder
.setMessage("Play again! \nScore: " + total_score + "\nTime: " +
time_done + " seconds" + "\n Unflagged Mines:" + unflagged_mines)
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
ResetTheGame();
}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
答案 0 :(得分:0)
你致电save(null);
并尝试使用该参数访问对象,即null
,导致NullPointerException
,导致应用程序崩溃
public void save(Context context) {
System.out.println("Running save");
settings = context.getSharedPreferences("Settings", Context.MODE_PRIVATE);