我很尷尬有這樣一個簡單的問題,但我只是不知道我做錯了什麼。我試圖在得分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);
}
}
}
感謝這麼多的一切,
根據你的標籤,這與數組和字符串有什麼關係?你確定每次都使用同一個類的實例嗎? –
您可能還想將'firstTimeOne'保存到您的首選項。否則,只要活動重新開始,它就會爲零。 –
*「雖然我不認爲這是必要的」*這是至關重要的,因爲你的問題並沒有說明firstTimeOne被聲明或初始化的位置或方式,或者在上面的代碼運行後會發生什麼,或者上面的代碼是如何跑。 –