Xetron
Xetron

Reputation: 121

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);

Upvotes: 0

Views: 63

Answers (1)

Eran
Eran

Reputation: 393781

You are missing commit or apply:

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

Without it, your changes to SharedPreferences are not persisted.

Upvotes: 5

Related Questions