简体   繁体   English

为什么每次打开活动时整数变量都不会增加1?

[英]Why won't an integer variable increment by 1 everytime an activity is opened?

In my activity below, I have an integer called test. 在下面的活动中,我有一个称为test的整数。 I want this integer to add 1 to itself every time the activity is opened and then get a toast to display its value. 我希望此整数在每次打开活动时对其自身加1,然后举杯以显示其值。 I have done this, but every time I open the activity the value is always printed in the toast as 1. Why is this? 我已经这样做了,但是每次我打开活动时,该值总是在烤面包上打印为1。为什么这样做?

int test = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hangar);

        final SharedPreferences saving = getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        final SharedPreferences.Editor editor = saving.edit();

        test = saving.getInt("testing", 0);

        test++;
        Toast.makeText(this, "Hello There " + test, Toast.LENGTH_SHORT).show();
        editor.putInt("testing", test);

You are missing commit or apply : 您缺少提交申请

editor.putInt("testing", test);
editor.commit ();

Without it, your changes to SharedPreferences are not persisted. 没有它,您对SharedPreferences所做的更改将不会保留。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM