简体   繁体   中英

Cannot load string from Fragment's shared preferences

I am trying to save and load a string value from a fragment's shared preferences. However, the string I am committing to the preferences does not load back from the preferences. Here is my code.

// Prefs string handle
String NAME = "myPref";

// Get default prefs for the fragment
SharedPreferences defaultPrefs = 
    PreferenceManager.getDefaultSharedPreferences(getActivity());

// Commit a string to prefs
defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();

// Load the string just commited to prefs
String commitedString = defaultPrefs.getString(NAME,"defaultString");

// Print the loaded string
// logs defaultString
// does not log Hello world!
Log.v(TAG,"commitedString value is "+commitedString);

You are editing, putting a String, not committing, then editing again, putting nothing, and then committing.

Change

defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();

To

defaultPrefs.edit().putString(NAME, "Hello world!").commit();

change this

defaultPrefs.edit().putString(NAME, "Hello world!");
defaultPrefs.edit().commit();

to this:

    SharedPreferences.Editor editor = defaultPrefs.edit();
    editor.putString(NAME, "Hello world!");
    editor.commit();

and it should work

//This always seemed to work for me
Context context = YourFragmentName.this;
String NAME = "";

SharedPreferences share = context.getSharedPreferences("prefs", 0);
share.getString(NAME, NAME);
SharedPreferences.Editor editor = share.edit();
editor.putString(NAME, "myPref");
editor.apply();

//then get your string
String commitedString =  share.getString(NAME, "");

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