简体   繁体   中英

Using GetDefaultSharedPreferences - SharedPref values reset between Activities

So, I have two activities in my application - StartActivity and SettingsActivity.

In StartActivity (launch activity) - I read the level and sound values from SharedPref. If they are not set, I set them to the default values, else I take the values found. Following code is inside the OnCreate of StartActivity.

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

String levelValue = sharedPref.getString(getString(R.string.levelpref), null);
String soundValue = sharedPref.getString(getString(R.string.soundpref), null);

if(levelValue == null)
{
    String levelDefaultValue = (getResources().getStringArray(R.array.level))[0];
    String soundDefaultValue = (getResources().getStringArray(R.array.sound))[0];

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(getString(R.string.levelpref), levelDefaultValue);
    editor.putString(getString(R.string.soundpref), soundDefaultValue);
    editor.apply();
}

In the SettingsActivity, I have a save button that saves newly set values for sound and level

public void saveSettings(View v)
{
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(getString(R.string.levelpref), level);
        editor.putString(getString(R.string.soundpref), sound);
        editor.apply();
}

Now, when I launch my app - StartActivity starts up - sees that the SharedPref values for sound and level are not setup and so assigns a default value. Next I move to settings activity, set new values for sound and level and save (from the debugger I was able to verify that new values are set).

But, when I come back to my StartActivity, the SharedPref values are for some reason reset back to the default values set before. From SO discussions, I read that using getDefaultSharedPreferences should retain values between activities.

Any ideas on what the problem is ?

Min-sdk version: 11 Target-sdk version: 18

我发现每次在onResume上都要重新打开PreferenceManager.getDefaultSharedPreferences(this),或者在可能的变化后检查。

i think you work with two different SharedPrefrence as that method you used related to context and contexts are different on 2 activity or you dont save your editor object. maybe this code help you :

    SharedPreferences setting = getSharedPreferences("HomeSetting", 0);
    Editor editor = setting.edit();
    editor.putBoolean(SERVICE_ON_VALUE, false);
    editor.commit();

hope to be useful :)

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