[英]Storing Application context in SharedPreferences when app crashes
[英]Sharedpreferences crashes the app when trying to retrieve
我剛接觸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();
}
}
}
您調用save(null);
並嘗試使用該參數訪問該對象,該參數為null
,從而導致NullPointerException
,使您的應用程序崩潰
public void save(Context context) {
System.out.println("Running save");
settings = context.getSharedPreferences("Settings", Context.MODE_PRIVATE);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.