为什么我的整数总是为零?

时间:2015-12-13 09:57:49

标签: android

我很尴尬有这么简单的问题,但我不知道自己做错了什么。我试图在得分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,但在`edit.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);
            }
        }
    }

非常感谢所有事情,

1 个答案:

答案 0 :(得分:3)

您的int变量是Activity类的成员,您在活动的onCreate()回调中检查它,该回调仅在实例化活动时调用。您的活动的每个实例都会重新实例化,成员变量将获得其默认值。这与你写的后来读的不一样。

如果要跨活动实例保留数据,请考虑使用例如SharedPreferences

相关问题