Reputation: 8945
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);
Upvotes: 0
Views: 51
Reputation: 70
//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, "");
Upvotes: 0
Reputation: 3107
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();
Upvotes: 2
Reputation: 1081
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
Upvotes: 0