Alex Rivera | Logout

sharedPreferences won't share between activities

Asked 2012-07-31T19:35:36.200
24

I'm trying to use SharedPreferences to save settings. But I can't seem to get the data to be shared between any of my activities. The code I'm using does manage to save settings but each activity seems to have it's own version of each variable.

So for example. I have an audio settings activity in which the user can give a value to a variable "musicVolume" which is saved. If I close the game and reload it, then the audio settings activity "remembers" the value. But if I try to load the value into any other activity it doesn't work. But, they can all load and save their own variables of the same name.

These are the methods I'm using to save the variables. There is a copy of each of these methods in each activity.**

As I say, they work, but they can only seem to read and write data for the individual activity in which they are located.

public void SavePreferences(String key, float value) {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putFloat(key, value);
        editor.commit();
}

public void LoadPreferences() {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        musicVolume = sharedPreferences.getFloat("musicVolume", (float)0.123);
        soundEffectsVolume = sharedPreferences
                        .getFloat("soundEffectsVolume", (float)0.123);
}

public void ClearPreferences() {
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
}

** I know there is a better way to do this but I'm a very novice oo programmer. I tried to follow the advice of another thread

Android Shared Preferences

but wherever I tried to put the lines

Edit
Report

1 Answer

9

If you aren't doing anything fancy with preferences I would just use the default way of accessing them. It seems to be your problem.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

Here is a great write with more detail, put you are doing everything pretty much correctly except for the getting your handle. How do I get the SharedPreferences from a PreferenceActivity in Android?

ALSO: Don't forget the new way is to call .apply() instead of .commit() This was in one on the #io2012 videos..

answered 2012-07-31T19:51:27.683

Your Answer