2012-07-29 64 views
0

我試圖存儲一個值來保持每次我重新創建一個名爲GameActivity類的活動的分數。我把下面的代碼段在我onCreate()方法:SharedPreferences變量不能正常工作

SharedPreferences settings = getSharedPreferences("Score", 0); 
    int lastscore = settings.getInt("Score", 0); 
    score=lastscore; 
    mScoreView.setText("Score: "+ score); 

mScoreView是假設每個活動重新創建時間與當前分數來更新一個TextView對象,score是一個實例變量。每個遊戲結束時都會彈出一個按鈕,讓用戶通過重新創建活動來繼續玩遊戲。下面是該按鈕的點擊監聽器:

private class MyButtonListener2 implements OnClickListener { 

    public void onClick(View v) { 
     State player = mGameView.getCurrentPlayer(); 
     Bundle myBundle=new Bundle(); 
      firstGame=false; 

     if (player == State.WIN) { 
      if(player==State.WIN){ 
       SharedPreferences scoreSaved = getSharedPreferences("Score",0); 
       SharedPreferences.Editor edit = scoreSaved.edit(); 
       edit.putInt("Score", score++); 
       edit.commit(); 
       //onCreate(myBundle); 
     } 
      else{ 
       myBundle.putInt("score1", 0); 
       //onCreate(myBundle); 
      } 
       GameActivity.this.recreate(); 
       onCreate(myBundle); 
}} 

比分是假設一個每個遊戲與人類玩家獲勝(State.WIN)結束時間遞增。但是,分數沒有正確更新。我在輕鬆沒收錯誤

+0

得分++將第一家店的分數,然後遞增一... – Shark 2012-07-29 13:06:15

回答

1

使用:

edit.putInt("Score", ++score); 

edit.putInt("Score", score + 1);