SharedPreference Changes not reflected in my wallpaper service

家住魔仙堡 提交于 2019-12-04 07:37:02

Solved!

I was setting values incorrectly in my PreferenceActivity and i didn't implemement OnSharedPreferenceChangeListener properly.

Solution :-

 ListPreference listPreference;

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.prefs);        
    listPreference = (ListPreference) findPreference("listPref");

}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    SharedPreferences customSharedPreference = getSharedPreferences(key, LiveWallpaperSettings.MODE_PRIVATE);
    SharedPreferences.Editor editor = customSharedPreference.edit();
    editor.putString("Speed",listPreference.getValue());
    editor.commit();
    Log.e("LiveWallpaperSettings", "Speed Value after setting " + customSharedPreference.getString("Speed", ""));
}



@Override
protected void onResume() {
    super.onResume();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();
    // Unregister the listener whenever a key changes
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

A couple of things: Your XML says that your key is "listPref", so when you're reading in the value from the prefs, you want to check for this key (Speed is just the display title)

I'm not convinced the preference changed listener is useful... The way that I would suggest, is that in your onResume() you would read the new value out of the preferences and use this value. This should work fine as everytime you return to your app after changing preferences, onResume() should be called.

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