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.
Related
I am attempting to do something I'm unsure of, and need someone to provide feedback.
I have 2 preferences. One of them, I want dependent on the other one's value.
Example: My "Notification Mode" Preference has 2 options: "Timer", and "Reminder"
If the User chooses the "Timer" option, I want my other Preference available to set time.
Otherwise, I want the Preference for setting the Timer to be disabled.
Here's what I've come up with inside my pref changed listener:
if (key.equals(PREF_NOTIFICATION_MODE)) {
Preference notifModePref = findPreference(key);
notifModePref.setSummary(sharedPreferences.getString(key, ""));
if(!notifModePref.equals("Timer Mode")) {
Preference timerDurationPref = findPreference(PREF_TIMER_DURATION);
timerDurationPref.onDependencyChanged(notifModePref, true);
} else if(notifModePref.equals("Timer Mode")) {
Preference timerDurationPref = findPreference(PREF_TIMER_DURATION);
timerDurationPref.onDependencyChanged(notifModePref, false);
}
}
I'm not sure if I'm doing this correctly, or if onDependencyChanged is proper.
I accomplished the Goal inside of if(key.equals) by referencing the Preference in question and using if statements and a combination of using onDependencyChanged(), and setting .isEnabled(boolean) as required.
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.
On the picture you can see that the boolean variable took the default value, even though there was a key-value pair in the SharedPreferences with the right key. What can cause this? In the code this is at the end of an onCreate method. After this the onMapReady method gets called (from com.google.android.gms.maps.OnMapReadyCallback), where I check the SAME boolean value, to see If i have to place some markers on the map or not. In that method the getBoolean() behaviour is correct, the default value is ignored. This doesn't make any sense to me, anyone can help me out?
1) Did you intend the space in the key "isThereReservation " ? In your debug code, the variable doesn't have a space. Make sure you use the right key else you'll get the default value!
2) How are you saving the sharedPref? your code should be:
myPrefs = myContext.getSharedPreferences("MY_PREFERENCE_NAME", MODE_PRIVATE);
myPrefEditor = myPrefs.edit();
myPrefsEditor.clear();
myPrefsEditor.putBoolean("MY_KEY",myBool);
and then you can access by using:
myPrefs = myContext.getSharedPreferences("MY_PREFERENCE_NAME", MODE_PRIVATE);
myPrefs.getBoolean("MY_KEY",MY_DEFAULT_VALUE);
The method getBoolean return default value if the key doesn't exist. In your case, the default value is false and if the key of the SharedPreference doesn't exist is false in your case.
You are showing in debug the value of the HashMap mMap but what is the content of the eu.arrowhed.arrowheaddemo for the same key?
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/
I'm a bit new to android dev. I have a preference screen on my app with a bunch of EditTextPreference and checkbox pref. I'm interested in doing validation on the input to the edittextpreference. It seems there is no way to do this using android, so I have developed a class that extends the edittextpreference.
For example, I have a text preference that only has a valid range of 0 to 1. The text preference will take in any numbers, but I need to validate this before setting.
I'm overriding the setText method, and trying to do validation there before actually setting the value. SetText only passes in the text string, how do I know what I am trying to validate? How can I get that information? In other words, I'd like to reuse my class to validate all of my text preferences, and I'd like something in the preference itself to tell me what type it is, or what it's range is.
Preference pref = findPreference("OutputFolder");
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
// Do the validation here
}
return true;
}
});