When the user updates a shared preference through a subclass of PreferenceActivity I check whether or not the new value is valid at the given time. If not the value should be changed back in the onSharedPreferenceChanged method.
This works so far. I set an OnSharedPreferenceChangedListener, the method gets called. The user-set value will be overwritten and the new value will be used in the app, however when I open this specific preferences value (in this case a ListPreference) again the wrong list item will be selected (the one the user selected, not the one set in the Listener). I tried overwriting the value with both:
mPrefs.edit().putString("answers", value.toString()).commit();
mPrefs.edit().putString("answers", value.toString()).apply();
Are there additional steps I need to take to update the ListPreference? After restarting the PreferenceActivity the value will be displayed correctly.
try to use Override method SharedPreferenceChanged
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY)) {
Preference ServicePref = findPreference(key);
// Set summary to be the user-description for the selected value
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
}
}
I found a way to solve this issue by setting the value manually as described here:
http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Related
Greetings my fellow developers,
i am working on an android project in there is a need to store the user name in shared preferences. and do a bit of validation when user tries to update his/her name in the app settings, i am using EditTextPreference for this preference, and i am implementing onPreferenceChangeListner to get updated value and do some validation on the updated value
here is my listner
#Override
public boolean onPreferenceChange(Preference preference, Object object) {
String value = object.toString().trim();
preference.setSummary(value);
if (value.isEmpty()) { // this block works as expected
preference.getEditor().clear().apply();
Log.i("pref_old", preference.getExtras().getString("key", "-- old value cleared --")); // this always shows old value cleared - as expected
return false;
}
preference.getEditor().putString("key", value).apply(); // this doesn't seems to be updating the value
Log.i("pref_new", preference.getExtras().getString("key", "-- new value not created --")); // this always show "new value not created", but it should show updated value
return true;
}
in this listner what i am trying to accomplish is to trim what user has entered, after that if string becomes empty remove the preference values so and update preferences
if not then update trimmed value in the preferences,
but problem is that after user enters the values, after trimming it value is not updated in shared preference. (in second part of the function)
it would seem that we need to always return false, if we are changing preference value in onPreferencechange and update preference value manually
i still dont understand why after comiting values in preference when i try to log the new value it wont show me updated value, but in other activity where the same value is being called i can go there and confirm that either value has changed or not
but solution to my problem was always return false and update preference value manually.
I have 2 fragments.
Fragment 1
Loads sharedpreference to display string
Fragment 2
Saves sharedprefence for string
Is it possible to retrieve that string in my first Fragment without running the second Fragment?
Yes, this is possible. You just need to make sure you are reading with the same key you used to write with:
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Reading from SharedPreferences
String value = prefs.getString("myKey", "defaultValue");
Log.d(LOG_TAG, value);
Note that we've assigned a defaultValue as the return value here. If there is no value with the key "myKey" in your shared prefs, it will instead return "defaultValue". This is a nice safeguard, think of it like a null pointer check - you will always get a value from getString(), even if it's just the default.
You don't need to be in the same activity for this to work, you just need to make sure that 1) your preferences name is the same and 2) the key used to store the value is the same in both spots.
First, don't get confuse between Activity and Fragment.
And yes, you can.
I have a problem in the LiveWallpaper app (my first) I am developing.
Consider 2 classes: LiveWallpaperService and LiveWallpaperSettings.
LiveWallpaperSettings extends PreferencyActivity. Example data representing
the preferences selected by the user, for example a boolean displaySprite (true=> display the sprite on the screen, false do not display) are saved/persisted via SharedPreferences in LiveWallpaperSettings.
Upon starting the application (Settings -> Display -> LiveWallpaper -> MyLiveWallpaper), the saved preferences need to be known so that the sprite can be displayed or not.
However, LiveWallpaperSettings is not instantiated until the Settings button is clicked, so SharedPreferences is not available, and thus saved settings are unavailable until then.
I tried this in LiveWallpaperService.onCreateScene(), but it has no data in it:
SharedPreferences startupPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
What can I do?
There is a default value if the entry/sharedpref file does not exist:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean display = settings.getBoolean("display", true);
"public abstract boolean getBoolean (String key, boolean defValue)"
Added in API level 1
Retrieve a boolean value from the preferences.
Parameters
key The name of the preference to retrieve.
defValue Value to return if this preference does not exist.
Hope I didnt misunderstood your question :)
In your preferences xml set the default value and in your MainActivity onCreate() add the following code setDefaultValues(this, R.xml.yourxmlname, false);
I've implemented a OnPreferenceChangeListener on two preference object in my preference page ( extends PreferenceActivity)
But ever since the preference value isn't updated upon change,
I even tried using :
SharedPreferences sharedPreferences = getSharedPreferences("myCustomSharedPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(preference.getKey(), Integer.parseInt(newValue.toString()));
editor.commit();
Where preference is the changed preference and newValue is the new value...
What am I missing ?
Thanks
You need to return true to get the value updated, see the Android documentation.
Can you see if preference.getKey() is giving the correct name? Can you print in your console and see. Code looks clean to me. May be the name is different than what is expected.
Also make sure that the value is also having the correct value.
I have an app which uses the user's location. I have a dialog(pic below) asking user's permission to "Allow" or "Disallow" the app to use the user's location ( dialog pops up the first time users opens the app after installation OR when user tries to use the location based service while using user location is "Disallow"-ed by the user).
I also use preference item(a checkbox)(pic below) in PreferenceActivity where the user can the toggle his preference.
To change the value of the sharedpreference I have use this code
public void onClick(DialogInterface dialog, int id)
{
sharedPrefs =getSharedPreferences("prefs",MODE_WORLD_WRITEABLE);
Editor editor = sharedPrefs.edit();
editor.putBoolean("locationPermission", true);
editor.commit();
}
I had expected the checkbox value to change automatically depending on the dialog selection as the key "locationPermission" holds the value to the checkbox. But it is not so.
Now how do I map the dialog(pic 1) selection to the checkbox value(pic 2)?
The issue was solved by using
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
instead of
sharedPrefs = getSharedPreferences("prefs", MODE_WORLD_WRITEABLE);
You can call addPreferencesFromResource in the onCreate of your PreferenceActivity so that your UI is populated from the preferences.
Also, you may want to make sure that your CheckBoxPreference has android:persistent-"true" in its XML definition.