Android shared preferences not saving

时光怂恿深爱的人放手 提交于 2019-11-28 07:11:50
zrgiu

From the documentation:

Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.

Since that's a new Editor instance, your code should be more like this:

preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.apply();

Try another way of initializing your SharedPreferences variable:

SharedPreferences sf = PreferenceManager.getDefaultSharedPreferences(this);

You can also chain writing to sf with sf.edit().putString(string, value).commit();

In my case I had to add editor.apply(); before commit in order to work.

This is my code:

preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.apply();//I added this line and started to work...
editor.commit();

well, based on @zrgiu post, for me only worked adding editor.clear(); before use the Editor...so the final code will be something like:

preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putString(SETTINGS_BACKGROUND_IMAGE, "okok");
editor.commit();

;)

Bear in mind that you need the same activity to save and retrieve data. You can not use a method like

public String readValue(Activity activity, String key) {
    SharedPreferences sp = activity.getPreferences(Context.Mode_PRIVATE);
   //...
}

For receiving the same data from the same activity you need to call this method with the exact same activity which you had saved your data.

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