How to obtain the value of the key passed to onSharedPreferenceChanged - android

In my PreferenceFragment I have implemented a OnSharedPreferenceChanged listener. It works. and I am able to see in the Log.i that the "key" matches the property that I am modifying (a switch preference).
But what I am unable to determine is how can I obtain the 'value' of the key? I have been struggling with this for about a day and a half and I know it has to be possible.
public class PrefsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// set all text correctly
onSharedPreferenceChanged(null, "");
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference preference = findPreference(key);
Log.i("TAG", String.valueOf(key));
}
}

You need use sharedPreferences attribute to get the value of the key.
public class PrefsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// set all text correctly
onSharedPreferenceChanged(null, "");
}
#Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String value = sharedPreferences.getString(key, "");
Log.i("TAG", value);
}
}
The second parameter of getString() is a default value if the method does not find anything with that key (don't returns null)
You have to make sure that the type stored in the preferences corresponds with which you recover (String in this case). In other case you need use getInt(), or getFloat()...

I just got it like I do elsewhere in the program:
if (key.equals("save_login")) {
boolean saveLogin = AppObject.defaultPrefs.getBoolean("save_login", true);
if(!saveLogin) {
// clear login info that may already have been saved, by default 'true'
SharedPreferences.Editor ed = AppObject.defaultPrefs.edit();
ed.putString("username", "");
ed.putString("password", "");
ed.commit();
}
}

if ("my_switch_preference_key".equals(key)) {
boolean newValue = sharedPreferences.getBoolean(key, false);
// use the new value
}
Replace "my_switch_preference_key" with the actual switch preference key.

Its a little late but I think we don't have to if-else to obtain the value of a key by following code:
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Map<String, ?> all = sharedPreferences.getAll();
Object value = all.get(key);
Log.d("TAG", "Key is: " + key);
Log.d("TAG", "Value is: " + String.valueOf(value));
}
You got an Object value of the key.

Related

Change in shared preference not firing

I have a Floating Action Button in my layout. Users can choose the position of this button, left or right. This can be selected in the preferences.
The code to do this works OK, but a change in the preference is not detected by the listener.
If the app is restarted, the Floating Action Button is displayed according to the new preference, so I know the process with this preference works, but unfortunately the listener seems to fail.
What do I have to do to get the listener firing when the preference has changed?
Listener in my MainActivity:
private final SharedPreferences.OnSharedPreferenceChangeListener
mPositionFabListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e(TAG,"Are we getting here?");
// We do not get here when preference has changed. Why not??
// Code to update Floating Action Button to new position
}
};
I register the listener in the onResume() method of the MainActivity and unregister in the onPause().
#Override
protected void onResume() {
super.onResume();
PrefUtils.registerOnPrefChangeListener(mPositionFabListener);
}
#Override
protected void onPause() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onPause();
}
The registerOnPrefChangeListener method is declared in a seperate class:
public class PrefUtils {
public static boolean getBoolean(String key, boolean defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getBoolean(key, defValue);
}
public static void putBoolean(String key, boolean value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putBoolean(key, value);
editor.apply();
}
public static int getInt(String key, int defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getInt(key, defValue);
}
public static void putInt(String key, int value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putInt(key, value);
editor.apply();
}
public static void registerOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).registerOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
public static void unregisterOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).unregisterOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
}
UPDATE:
In the GeneralPrefsFragment class I put in this listener for testing purposes. This listener is working. So why does it not work in the MainActivity?
public class GeneralPrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Preference preference = findPreference(PrefUtils.POSITION_FLOATING_MENU_BUTTON);
Preference.OnPreferenceChangeListener mListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PrefUtils.putBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, Boolean.TRUE.equals(newValue));
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit().commit(); // to be sure all prefs are written
Log.e(TAG, "The listener in " + TAG + " is listening");
// This listener is fired as soon as changes in the preference are made!
// Why is the same kind of listener not fired in the MainActivity?
return true;
}
};
preference.setOnPreferenceChangeListener(mListener);
}
}
SOLUTION:
I got a fix. I still do not know why the former setup didn't work, but I got it working, thanks to the code in this answer.
In the MainAcivity's onCreate() method I placed the following listener and this one gets triggered when the preferences have changed.
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener mPrefsFabListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (PrefUtils.POSITION_FLOATING_MENU_BUTTON.equals(key)) {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams paramsFab = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
if (PrefUtils.getBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, false)) {
paramsFab.gravity = Gravity.BOTTOM | Gravity.START;
} else {
paramsFab.gravity = Gravity.BOTTOM | Gravity.END;
}
}
}
};
prefs.registerOnSharedPreferenceChangeListener(mPrefsFabListener);
The OnSharedPreferenceChangeListener gets unregistered in the onPause() method of the MainAcitivity. That is a problem, because the MainActivity gets paused as soon as the General Preferences Activity is started in order to change the preferences. So, the listener is unregistered and therefore not listening right at the point where it is needed!
I removed the unregisterOnPrefChangeListener from the onPause() and put in the following code. This worked perfectly!
#Override
protected void onDestroy() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onDestroy();
}

Android setOnPreferenceChangeListener not being called correctly

I have a ListPreferenece in my preference screen and when It changes I need to execute a method. Problem is when I first change the preferenece list nothing happens but it works the second time round...
public static class DisplayFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
cPPreference cPBg;
cPPreference cPFt;
cPPreference cPTm;
cPPreference cPLg;
ListPreference colorThemeList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.display_preferences);
cPBg = (cPPreference) getPreferenceScreen().findPreference("ambilBg");
cPFt = (cPPreference) getPreferenceScreen().findPreference("ambilFt");
cPTm = (cPPreference) getPreferenceScreen().findPreference("ambilTm");
cPLg = (cPPreference) getPreferenceScreen().findPreference("ambilLg");
/**
* When this list changes I need to exectue a method
*/
colorThemeList = (ListPreference) getPreferenceScreen().findPreference("colorTheme");
colorThemeList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
ThemeHandler.setTheme(cPBg, cPFt, cPTm, cPLg, colorThemeList.getValue());
return true;
}
});
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
setSummarys();
}
}
Any help greatly appreciated
O.k ...found solution
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("colorTheme")) {
ThemeHandler.setTheme(colorPickerBg, colorPickerFt, colorPickerTm, colorPickerLg, colorThemeList.getValue());
}
}
A simple check in the onSharedPreferneceChanged method :)

Android: Unable to get preference values from settings.xml

I have a settings.xml in my res folder to manage user settings. I load this into a fragment. I require to store these settings to a backend service for this I want to know what values have been by the user or whenever user changes a setting I want to know so that I update the server about the settings.
I have tried many approaches as shown in the code below but I am unable to read the value. I tried putting Toast and log statements to check the listeners but nothing is appearing which indicates that listener is not getting called. Am I doing something wrong?
UserSettingFragment.java
public class UserSettingFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
//Method 1
PreferenceScreen shared = getPreferenceScreen();
shared.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
Log.d("preference", "change");
return true;
}
});
final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Preference gender = (Preference) findPreference("gender");
//Method 2
// Get the custom preference
Preference mypref = (Preference) findPreference("mypref");
mypref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
String highScore = sharedPref.getString("gender", "Male");
Toast.makeText(getActivity().getApplicationContext(), "Changed to " + highScore, Toast.LENGTH_LONG).show();
Log.d("preference", "change");
return false;
}
});
} //Method 3
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
}
settings.xml
<?xml version="1.0" encoding="utf-8"?>
<SwitchPreference
android:key="gender"
android:title="I am"
android:switchTextOn="Female"
android:switchTextOff="Male"
/>
</PreferenceCategory>
Since you are using a PreferenceFragment you need to register and unregister OnSharedPreferenceChangeListener in the onResume and onPause methods for method #3 that you mentioned in your question.
public class UserSettingFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getActivity().getApplicationContext(), "Changed key: " + key, Toast.LENGTH_LONG).show();
}
}
Reference

EditTextPreference validate data before saving

I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!

Check and Format preference string value before committing back to preferences

I have an EditTextPreference. After the user has edited the preference and pressed ok I then want to check the value for formatting errors before committing.
public class Preferences_Default extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.prefs_default);
}
}
#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);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//This just calls a function to update the Pref Summary
Preference pref = findPreference(key);
initSummary(pref);
}
Where would I put the call to the function that checks the value and what is the code to re-commit the preference value if altered.
Friend, as you just specified, you have to check this in your code: you have to put it first line before it gets updated
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//function to check
boolean b=check();
//This just calls a function to update the Pref Summary
if(b)
{
Preference pref = findPreference(key);
initSummary(pref);}
else{
//whatever you want to do show error
}
}

Categories

Resources