无法从Fragment的共享首选项加载字符串

时间:2017-06-21 20:39:58

标签: android

我正在尝试从片段的共享首选项中保存并加载字符串值。但是,我提交给首选项的字符串不会从首选项加载回来。这是我的代码。

// 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);

3 个答案:

答案 0 :(得分:2)

您正在编辑,放置字符串,不提交,然后再次编辑,不做任何事情,然后提交。

更改

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

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

答案 1 :(得分:0)

更改此

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

到此:

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

它应该有效

答案 2 :(得分:0)

//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, "");