简体   繁体   中英

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

In my activity below, I have an integer called 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. I have done this, but every time I open the activity the value is always printed in the toast as 1. Why is this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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