Traijan
Traijan

Reputation: 73

Shared Preferences won't save the data

I'm new to Android, and a bit to Java (Don't ask)

I want to use the Shared Preferences, and till to this day everything worked fine, but in my new project the shared preferences won't save the data.

In my onCreate Method I have following code:

    preferences = this.getSharedPreferences(KEY, MODE_PRIVATE);
    editor = preferences.edit();
    preferences.getFloat(TESTEPFLOAT, 0);
    preferences.getFloat(TESTCURRENTEPFLOAT, 0);
    preferences.getInt(TESTLEVEL, 1);

in my onDestroy Method:

@Override
public void onDestroy(){
    super.onDestroy();
    editor.putInt(TESTLEVEL, level);
    editor.putFloat(TESTEPFLOAT, ep);
    editor.putFloat(TESTCURRENTEPFLOAT, currentEP);
    editor.apply();
}

I don't know where the problem is, and I hope someone can help me

Upvotes: 1

Views: 474

Answers (3)

devmike01
devmike01

Reputation: 1987

Just as @Gavin Wright said, onDestroy don't get called everytime. Move the code to onPause(). onPause() is guaranteed to get called everytime you navigate away from your activity.

@Override
public void onPause(){
    super.onPause();
    editor.putInt(TESTLEVEL, level);
    editor.putFloat(TESTEPFLOAT, ep);
    editor.putFloat(TESTCURRENTEPFLOAT, currentEP);
    editor.apply();
}

Upvotes: 0

Christos Themelis
Christos Themelis

Reputation: 189

change to this:

preferences = this.getSharedPreferences(KEY, MODE_PRIVATE);
preferences.getFloat(TESTEPFLOAT, 0);
preferences.getFloat(TESTCURRENTEPFLOAT, 0);
preferences.getInt(TESTLEVEL, 1);

to save your data:

@Override
    protected void onPause() {
        super.onPause();
    preferences = this.getSharedPreferences(KEY, MODE_PRIVATE);
        editor = preferences.edit();
        editor.putInt(TESTLEVEL, level);
        editor.putFloat(TESTEPFLOAT, ep);
        editor.putFloat(TESTCURRENTEPFLOAT, currentEP);
        editor.apply();
}

or use editor.commit(); to save data immediately

Upvotes: 1

Gavin Wright
Gavin Wright

Reputation: 3212

Don't use onDestroy(). There's no guarantee it will get called. If you put a break point in that method, my guess is it's not getting called when you think it is.

Upvotes: 4

Related Questions