2015-12-13 100 views
-1

我很尷尬有這樣一個簡單的問題,但我只是不知道我做錯了什麼。我試圖在得分20後解鎖關卡。第一次關卡解鎖時,我想給用戶一條消息,說明「關卡解鎖」。我這樣做,像這樣:爲什麼我的整數總是零?

if(firstTimeOne == 0 && currentHighOne.getInt("levelOneHigh", 0) >= 20){ //First time getting a score over 20 
       Toast.makeText(LevelSelect.this, "Unlocked level two!" +firstTimeOne, Toast.LENGTH_SHORT).show(); 
       firstTimeOne=1; 
      } 

的問題是,這種代碼執行時間的用戶得到一個得分超過20 ...的firstTimeOne變量應該防止的是,對不對?在調用此方法後,它被設置爲1,防止再次調用該方法。那麼,爲什麼這個方法不止一次被調用?

我把這些變量firstTimeOne在我的課,我在那裏寫:

int firstTimeOne = 0; 

如果你需要我的完整的代碼,在這兒呢。這表明我初始化int類型的類,而不是一個方法:

https://gist.github.com/anonymous/b52a5873b9eb9324e671

編輯:

好了,所以我想SharedPreferences,但得到`編輯一個空指針異常。 putInt(「firstInt」,1);下面是代碼:https://gist.github.com/anonymous/c5b71982559c245220df


//ints will be zero if they do not have a value assigned to them...right? 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_level_select); 

     levelTwoButton = (Button) findViewById(R.id.leveltwo); 

     SharedPreferences currentHighOne = this.getSharedPreferences("levelOneScore", Context.MODE_PRIVATE); 
     if (currentHighOne.getInt("levelOneHigh", 0) < 20) { 
      levelTwoButton.setClickable(false); 
      levelTwoButton.setText("Level two is locked!"); 
     }else{ 

      SharedPreferences firstTimeOne = this.getSharedPreferences("firstTimeOne", Context.MODE_PRIVATE); //Making a shared pref 

      if(firstTimeOne.getInt("firstInt" , 5) == 5) { //Check if I've stored values in it yet 
       edit = firstTimeOne.edit(); 
       edit.putInt("firstInt", 0); //Setting the default as 0 
       edit.commit(); 
      } 
      if(firstTimeOne.getInt("firstInt", 0) == 0 && currentHighOne.getInt("levelOneHigh", 0) >= 20){ //First time getting a score over 20 
       Toast.makeText(LevelSelect.this, "Unlocked level two!" +firstTimeOne, Toast.LENGTH_SHORT).show(); 

       edit.putInt("firstInt", 1); 
      } 
     } 
    } 

感謝這麼多的一切,

+2

根據你的標籤,這與數組和字符串有什麼關係?你確定每次都使用同一個類的實例嗎? –

+2

您可能還想將'firstTimeOne'保存到您的首選項。否則,只要活動重新開始,它就會爲零。 –

+3

*「雖然我不認爲這是必要的」*這是至關重要的,因爲你的問題並沒有說明firstTimeOne被聲明或初始化的位置或方式,或者在上面的代碼運行後會發生什麼,或者上面的代碼是如何跑。 –

回答

3

你的int變量是你Activity類的成員,而你在活動的onCreate()回調檢查它這是唯一當活動被實例化時調用。您的活動的每個實例都會重新實例化,並且成員變量將獲得其默認值。這是不一樣的,你寫的,你後來閱讀。

如果要在活動實例中保留數據,請考慮使用例如SharedPreferences

+0

好吧,所以我嘗試使用SharedPreferences,但在edit.putInt(「firstInt」,1)上得到空指針異常。這裏是代碼:https://gist.github.com/anonymous/c5b71982559c245220df –

+0

你的'SharedPreferences.Editor edit'沒有在你調用'putInt()'的分支中初始化。 – laalto

+0

那麼......我該怎麼做。我應該在可見範圍內創建一個新對象嗎?謝謝 –