SharedPreferences.Editor not being updated after initial commit

大城市里の小女人 提交于 2019-12-25 00:05:38

问题


I'ma a bit confused here. I'm trying to change the value of an EditTextPreference, but it is not updated in the view. (This is in a PreferenceActivity)

Here is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.modify_instrument_preferences);

  // Set default values
  SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
  SharedPreferences.Editor editor = customSharedPreference.edit();
  modifying = getObjectWithName(); //Some object with a name;

  editor.putString("namePref", modifying.getName());
  editor.commit();
  android.util.Log.d("TEST", "written: "+customSharedPreference.getString("namePref",""));
}

My printlns print out valid information, and the commit() returns true, but on clicking the EditTextPreference, it displays the old value. If I rotate the screen, causing the onCreate to get run again, the EditTextPreference has the right value.

So perplexing. Why isn't this change being updated in the UI?

Edit:

I'm not sure why the above isn't working, but I managed to change it just by doing:

  EditTextPreference namePref = (EditTextPreference) findPreference("namePref");
  namePref.setText("the text");

That updated the view everytime.


回答1:


Although I know there are some constructs in place for PreferenceActivities to keep track of this info themselves, it doesn't seem to be well documented. I have found that adding an onPreferenceChangeListener to the preference will allow you to make those edits as soon as the preference is changed.



来源:https://stackoverflow.com/questions/9050810/sharedpreferences-editor-not-being-updated-after-initial-commit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!