CheckBoxPreference - onSharedPreferenceChanged method not getting called - java

I have a couple of CheckBoxPreferences set up, my preference class extends PreferenceActivity and implements OnSharedPreferenceChangeListener
This is what I'm using to respond to people checking/unchecking the CheckBoxPreferences:
public void onSharedPreferenceChanged(SharedPreferences P, String K) {
if (K.equals(CheckBoxPref_KEY_HERE)) {
MyClass.BooleanVariable = P.getBoolean("CheckBoxPref_KEY_HERE", true);
}
}
As far as I can tell, the onSharedPreferenceChanged method above is never even getting called?

Here is the soln if you want to do something on all the preferences:
Create a class member:
SharedPreferences settings;
in your onCreate method:
settings = getSharedPreferences(<your_pref_name>, 0);
settings.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
// Do whatever
}
});

checkBoxPreference = (CheckBoxPreference) this.findPreference("CheckBoxPref_KEY_HERE");
checkBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// do your work here
return true;
}
});

Related

How to handle configuration change in Android keyboard (IME)?

I have been following Android sample provided with the documentation to design new (relatively simple) keyboard. At this point I am stuck with configuration change (like theme, textSize or bit complex stuff) which requires IME to recreate itself.
public class ImePreferences extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme_WithActionBar);
super.onCreate(savedInstanceState);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// reload ime
Log.d("anbani", "Stopping service " + String.valueOf(stopService(new Intent(this, SoftKeyboard.class))));
Log.d("anbani", "prefs changed");
}
...
}
This does not help. StopService value is returned true but there is no effect.
Is there some trick to get an instance of package keyboard without prior reference to it? Or am missing something simple here?
Any tips would be highly appreciated!
Solution:
#Override public View onCreateInputView() {
// load preferences
return mInputView;
}
#Override public void onStartInputView(EditorInfo attribute, boolean restarting) {
super.onStartInputView(attribute, restarting);
setInputView(onCreateInputView());
...
}

PopupDateField Listener

I've got a PopupDateField with a ValueChangeListener.
Is there a way to differentiate if the Event was fired from an .setValue()-Call or an User-Input?
I want the Event to be excuted only if the user changes the value, not if it was changed by program.
I've made a dirty Workaround by removing the ValueChangListener before setting a new Value and adding it afterwards, but I'm thankfull for better solutions...
private static void setDateFieldValue(final PopupDateField dateField, Date value) {
Collection<Property.ValueChangeListener> listeners = (Collection<Property.ValueChangeListener>)dateField.getListeners(Property.ValueChangeEvent.class);
listeners.forEach(new Consumer<Property.ValueChangeListener>() {
#Override
public void accept(Property.ValueChangeListener listener) {
dateField.removeValueChangeListener(listener);
}
});
dateField.setValue(value);
listeners.forEach(new Consumer<Property.ValueChangeListener>() {
#Override
public void accept(Property.ValueChangeListener listener) {
dateField.addValueChangeListener(listener);
}
});
}

onSharedPreferenceChanged isn't called everytime a preference has been changed

I have a problem with onSharedPreferenceChanged is only called the first time when a MultiSelectListPreference has changed. I open my settings activity and change the value which works fine and onSharedPreferenceChanged is getting called. If I open the dialog again, it shows the correct entries selected. I select another entry and hit OK. onSharedPreferenceChanged should now getting called but isn't. If I now open the dialog again, no entries are selected. Am I missing something or did I do somethign wrong?
Here's my preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<MultiSelectListPreference
android:key="operations"
android:title="#string/pref_operations"
android:dialogTitle="#string/pref_operations"
android:entries="#array/pref_operations_entries"
android:entryValues="#array/pref_operations_values"
android:defaultValue="#array/pref_operations_default" />
</PreferenceScreen>
And my settings fragment
public class SettingsFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener
{
public static final String KEY_OPERATIONS_PREFERENCE = "operations";
private MultiSelectListPreference operationsPreference;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
operationsPreference = (MultiSelectListPreference) getPreferenceScreen().findPreference(KEY_OPERATIONS_PREFERENCE);
}
#Override
public void onResume()
{
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
Set<String> operations = operationsPreference.getValues();
String summary = "";
for (String s : operations)
summary += s + " ";
operationsPreference.setSummary(summary);
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause()
{
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(KEY_OPERATIONS_PREFERENCE))
{
Set<String> operations = operationsPreference.getValues();
String summary = "";
for (String s : operations)
summary += s + " ";
operationsPreference.setSummary(summary);
}
}
}
Umm frankly I built my sharedPreferances differently...ill attach my code example and hopefully it'll be of use to you
here goes:
this is the sharedpreferences class
public class AppPreferences {
public static final String KEY_LANG = "language";
final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); // Name
// of
// the
// file
// -.xml
private SharedPreferences _sharedPrefs;
private Editor _prefsEditor;
public AppPreferences(Context context) {
this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS,
Activity.MODE_PRIVATE);
this._prefsEditor = _sharedPrefs.edit();
}
public String getlanguage() {
return _sharedPrefs.getString(KEY_LANG, "");
}
public void savelanguage(String text) {
_prefsEditor.putString(KEY_LANG, text);
_prefsEditor.commit();
}
}
to use it youll need to create
in your class
private AppPreferences _appPrefs;
and an example for use is
_appPrefs = new AppPreferences(getApplicationContext());
_appPrefs.savelanguage("English");
language = _appPrefs.getlanguage();
this is how i built it... works like a charm... and not complicated at all
It's because you unregister the listener in your onPause callback method which is invoked when Dialog is shown in an Activity.

Shared preferences don't take effect until Preferences clicked

I'm writing an app for the Sony Smartwatch, using their SDK. Here's part of the main activity:
class SmartTickerActivity extends ControlExtension {
private Handler mHandler;
SmartTickerActivity(final String hostAppPackageName, final Context context, Handler handler) {
super(context, hostAppPackageName);
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
}
#Override
public void onStart() {
//do some stuff
PreferenceManager.setDefaultValues(mContext, R.xml.preference, false);
}
The problem is that the saved preferences aren't being applied on the Smartwatch when the application launches. Nor are the default preference values from XML. However, if I click on any of the app's preferences on the phone, the saved preference values are immediately applied to the Smartwatch.
Note that the main class has no onCreate() method, and that's throwing me for a loop.
Here's part of the Preference activity:
public class MyPreferenceActivity extends PreferenceActivity {
private OnSharedPreferenceChangeListener mListener = new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry().toString());
}
if (pref instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
pref.setSummary(editTextPref.getText().toString());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preference);
setSummaries();
setTypeface(SmartTickerActivity.mainLayout);
if (previewLayout != null) setTypeface(previewLayout);
// Handle read me
Preference readMe = findPreference(getText(R.string.preference_key_read_me));
readMe.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference readMe) {
showDialog(DIALOG_READ_ME);
return true;
}
});
// Handle about
Preference about = findPreference(getText(R.string.preference_key_about));
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference about) {
showDialog(DIALOG_ABOUT);
return true;
}
});
// Handle preview
Preference preview = findPreference(getText(R.string.preference_key_preview_dialog));
preview.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preview) {
showDialog(DIALOG_PREVIEW);
return true;
}
});
}
I'm rather inexperienced at Android development, so the problem might very well have nothing to do whatsoever with the Sony SDK. Can anyone help?
You are correct, the preferences of the official sample extensions are not loaded until the PreferenceActivity is shown for the first time. If you use correct default values when accessing the preferences, this should not be a problem.
If you would like for the preferences to be loaded when the extension is initiated the first time, you could extend the android.app.Application class, and the onCreate method.
For example:
public class MySmartWatchApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
PreferenceManager.setDefaultValues(this, R.xml.app_preferences, false);
}
}

Adding support for settings screen android

I'am using several CheckBoxPreference in my android app to add a settings menu. But is there a way to say that one and only one CheckBoxPreference MUST be checked at the time?
Here's one way to do it, but it could certainly be improved!
public class Settings extends PreferenceActivity{
CheckBoxPreference cb1;
CheckBoxPreference cb2;
CheckBoxPreference cb3;
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
addPreferencesFromResource(R.xml.preferences);
cb1 = (CheckBoxPreference) findPreference("CheckBox1");
cb2 = (CheckBoxPreference) findPreference("CheckBox2");
cb3 = (CheckBoxPreference) findPreference("CheckBox3");
cb1.setOnPreferenceChangeListener(new Listener());
cb2.setOnPreferenceChangeListener(new Listener());
cb3.setOnPreferenceChangeListener(new Listener());
}
private class Listener implements OnPreferenceChangeListener {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if((Boolean) newValue)
removeOthers(preference.getKey());
return true;
}
}
private void removeOthers(String key) {
if(key.equals("CheckBox1")) {
cb2.setChecked(false);
cb3.setChecked(false);
}
else if(key.equals("CheckBox2")) {
cb1.setChecked(false);
cb3.setChecked(false);
}
else if(key.equals("CheckBox3")) {
cb1.setChecked(false);
cb2.setChecked(false);
}
}
}
This is pretty basic logic:
int numOfCheck = 0;
//Check each checkbox
if(checkbox1.checked){
numOfCheck+=1;
}
//... Add other checkboxes
if(numOfCheck>1||numOfCheck<1){
//... Alert the user
}
It's simple: RadioGroup.

Categories