Setting CheckBoxPreference from SharedPreference - android

I'd like to use pre-defined shared preferences to set the value of a checkBoxPreference, and to set the shared preference with the checkBoxPreference. I tried this code, but checkboxPref always ends up being null even though I know "pre_definied_shared_prefs" exist.
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("pre_defined_shared_prefs");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean b = (Boolean) newValue;
Intent i = getIntent();
Integer show_num = i.getIntExtra("show_num", -1);
SettingsManager s = new SettingsManager();
s.setShowNotification(show_num, b, getApplicationContext());
return true;
}
});
Why would this be and how can I fix it?

My preference.xml:
<CheckBoxPreference
android:title="Show Call UI"
android:defaultValue="true"
android:summary="Show Call Interface when clicking call button"
android:key="checkboxPref" />
Rest code:
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());
return true;
}
});
Here is the example on how to create new checkbox preference and add it to the group you wished or look at this
public class MyPreferenceActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.my_preference_activity);
//fetch the item where you wish to insert the CheckBoxPreference, in this case a PreferenceCategory with key "targetCategory"
PreferenceCategory targetCategory = (PreferenceCategory)findPreference("targetCategory");
//create one check box for each setting you need
CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
//make sure each key is unique
checkBoxPreference.setKey("keyName");
checkBoxPreference.setChecked(true);
targetCategory.addPreference(checkBoxPreference);
}
}

Related

Check if switch from SettingsActivity is on

How can I check in my MainActivity if the on/off switch is on in the SettingsActivity. I want to check if the switch is on and if it is, I want to do something. How do I do this so that this preference is saved and will be the same when you restart the app?
Here is a part of my SettingsActivity with a switch
static int audio;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
return true;
}
});
}
You are saving correctly the preference value, even you are returning true from your onPreferenceChangeListener to store the new value.
Preference switchPref = (Preference) findPreference("audio_switch");
switchPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
boolean isOn = (boolean) o;
if (isOn) {
audio = 1;
}else{
audio = 0;
}
//* Set true to update the state of the Preference with the new value!
return true;
}
});
}
The value is saved correctly when you close the application, if you want to check the value you can read it from the preference:
//Check the current value in preference.
SharedPreferences switchPrefStatus = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean switchPrefValue = switchPrefStatus.getBoolean("audio_switch", false);
Toast.makeText(getActivity(), "Current value: " + switchPrefValue, Toast.LENGTH_SHORT).show();
Here is a complete example of PreferenceFragment with PreferenceFragment:
I usually do the following:
To save your setting
(Put this in a save() method you call when you click a button or something in your settings activity)
SharedPreferences options =
getSharedPreferences("optionsPreference",
contextOfSettings.MODE_PRIVATE);
options.edit().putString("key", "value").apply();
In order to do this you need to add this in your settings activity
As a global variable in settings
public static Context contextOfSettings;
And this method in your onCreate of settings
#Override
protected void onCreate {
contextOfSettings = getApplicationContext();
}
And import it in your main activity by typing context of settings somewhere and then import it by pressing alt+enter
Like this:
import com.SettingsActivity.contextOfSettings;
Then you can get your saved value (which will still be saved even if you close your app) with this in your on create of your MainActivity
SharedPreferences options = getSharedPreferences("optionsPreference", contextOfSettings.MODE_PRIVATE);
String savedValue = options.getString("key", "defaultValue");
This String can have the values true and false which you can set with checkBox.isChecked() in combination with an if-statement

Android: update ListPreference with OnPreferenceChangeListener

Here's my preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<ListPreference
android:key="KEY_1"
android:title="Title"
android:summary="Summary"
android:dialogTitle="Dialog"
/>
<ListPreference
android:key="KEY_2"
/>
<ListPreference
android:key="KEY_3"
/>
<ListPreference
android:key="KEY_4"
/>
And here is the Settings.java:
public class Settings extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// some methods to generate entries and values for ListPreference
final List List_1 = // something
final List List_2 = // something
final List List_3 = // something
String[] entry_1 = List_1.toArray(new String[List_1.size()]);
String[] entry_2 = List_2.toArray(new String[List_2.size()]);
String[] entry_3 = List_3.toArray(new String[List_3.size()]);
String[] value_1 = List_1.toArray(new String[List_1.size()]);
String[] value_2 = List_2.toArray(new String[List_2.size()]);
String[] value_3 = List_3.toArray(new String[List_3.size()]);
// set arrays for entries and values
final ListPreference lp1 = (ListPreference)findPreference("KEY_1");
lp1.setEntries(entry_1);
lp1.setEntryValues(value_2);
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setEntries(entry_2);
lp2.setEntryValues(value_1);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setEntries(entry_2);
lp3.setEntryValues(value_2);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setEntries(entry_2);
lp4.setEntryValues(value_3);
// update lp2, lp3, lp4
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String listValue = (String) newValue;
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setDefaultValue(listValue);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setDefaultValue(listValue);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setDefaultValue(listValue);
return true;
}
});
}
}
This works well for me for only one time. What am I missing here to make the updates on lp2, lp3 and lp4 later on? I guess setDefaultValue creates just that one-time-input to shared preferences?
I suspect your anonymous listener is garbage collected - add some debug prints to see if the listener is called
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("Listener", "I listen");
String listValue = (String) newValue;
// rest is the same
}
});
If you see no debug print move your listener to a class field and :
public class Settings extends PreferenceActivity {
private OnPreferenceChangeListener mListener=new OnPreferenceChangeListener(){
#Override
public boolean onPreferenceChange(Preference preference, Object newValue){
// as before
}
};
// etc - I guess the line below is in onCreate() - correct your formatting !
lp1.setOnPreferenceChangeListener(mListener);
}
}

Custom EditTextPreference and setOnPreferenceChangeListener not called

My listener is not getting called for some reason? This is what I have:
In Preference file I have a custom EditTextPreference:
<com.xxx.yyy.preference.PreferenceEditTextDialog
android:layout="#layout/preference_edit"
android:title="#string/title"
android:summary="#string/summary"
android:defaultValue=""
android:dialogTitle="#string/dialogTitle"
android:key="mypref"/>
I extend my class:
public class PreferenceEditTextDialog extends EditTextPreference {
Launching my Activity:
startActivity(new Intent(this, PrefsActivity.class));
Definition:
public class PrefsActivity extends PreferenceActivity implements
OnPreferenceClickListener, OnSharedPreferenceChangeListener {
In here I register my setOnPreferenceChangeListener (which is not called).
However changing my Preference file from:
<com.xxx.yyy.preference.PreferenceEditTextDialog
to default:
<EditTextPreference
it all works. Could someone help me to find the problem, somehow the listener is not propagated properly using my custom Preference.
Thanks!
#Sam Here my listener definition:
myfield = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREFERENCE);
myfield.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean valid = true;
if(!validate(newValue.toString())) {
valid = false;
}
return valid;
}
});
Found a solution, in my custom EditTextPreference I added a call to callChangeListener(value):
#Override
public void onBindDialogView(View view) {
edittext = (EditText) view.findViewById(R.id.edittext);
edittext.setText(PreferenceManager.
getDefaultSharedPreferences(view.getContext()).
getString(getKey(), ""));
ok_button = (Button) view.findViewById(R.id.ok_button);
ok_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String value = edittext.getText().toString();
if(callChangeListener(value)) {
Editor editor = getEditor();
editor.putString(getKey(), value);
editor.commit();
getDialog().dismiss();
}
}
});

CheckBox PreferenceScreen

I am doing a preferenceScreen with this xml code:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:orderingFromXml="true">
<PreferenceCategory
android:key="pref1"
android:title="Search All">
<CheckBoxPreference
android:key="check_all"
android:title="Check"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Specific Search"
android:key="pref2">
<ListPreference
android:title="Food"
android:key="opcion1"
android:dialogTitle="Escoge Categoria"
android:entryValues="#array/codigoCateg"
android:entries="#array/categorias"
android:negativeButtonText="Cancel"/>
<ListPreference android:title="Dificultad"/>
<ListPreference android:title="Otras"/>
</PreferenceCategory>
Java code:
public class OpcionesBusqueda extends PreferenceActivity {
boolean CheckBoxPreference;
private PreferenceCategory Pref2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.video_search);
Pref2=(PreferenceCategory)findPreference("pref2");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckBoxPreference = prefs.getBoolean("check_all", true);
if(CheckBoxPreference==true){
Pref2.setEnabled(false);
}
else{
Pref2.setEnabled(true);
}
}
}
What I would like to do is if the checkbox is checked then the pref2 (preferencecategory2) should be disabled and if it is unchecked, it should be enabled. There is something that I'm doing wrong, or maybe more than one.
Thanks.
I followed Alex's answer and with some changes I arrived to the desire code, here is the code corrected:
public class OpcionesBusqueda extends PreferenceActivity {
private CheckBoxPreference Check;
private PreferenceCategory Pref2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.video_search);
Check=(CheckBoxPreference)findPreference("check_all");
Pref2=(PreferenceCategory)findPreference("pref2");
Check.setOnPreferenceChangeListener(new CheckBoxPreference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
Pref2.setEnabled((Boolean)newValue == false);
return true;
}
});
}
You may want to set OnPreferenceChangeListener for the check_all preference and change pref2 inside onPreferenceChaged of that OnPreferenceChangeListener
CheckBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
boolean onPreferenceChange(Preference preference, Object newValue) {
Pref2.setEnabled((Boolean)newValue == false);
}
}

Android Checkbox preference

I cannot find any tutorials on checkbox preference. I can use a listpreference, but I can't use checkbox preference. For now, I want that if user sets on the checbox, a toast msg says "true" and if he sets it off, the toast msg says "false". So far I have this:
preferences.xml:
<CheckBoxPreference
android:title="Show Call UI"
android:defaultValue="true"
android:summary="Show Call Interface when clicking call button"
android:key="checkboxPref" />
EditPreferences.java:
public class EditPreferences extends PreferenceActivity {
String listPreference;
boolean checkboxPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
public void onStart(Intent intent, int startId) {
getPrefs();
}
private void getPrefs() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
listPreference = prefs.getString("listPref", "nr1");
checkboxPreference = prefs.getBoolean("checkboxPref", true);
}
}
Edit: Solution thanks to David Caunt:
checkboxPreference.
setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("true")) {
Toast.makeText(getApplicationContext(), "CB: " + "true",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "CB: " + "false",
Toast.LENGTH_SHORT).show();
}
return true;
}
});
You need to add a listener to the Preference in your onCreate method
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());
return true;
}
});
You can cast the value of the checkbox into a boolean. This might be safer and more extensible than checking the toString() value.
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue instanceof Boolean){
Boolean boolVal = (Boolean)newValue;
}
return true;
}
});
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Log.i("LOG", String.valueOf(sp.getBoolean("key", false)));
Simplest way i found of getting value if item is pressed. If log is:
I/LOG: true
Checkbox is pressed
I/LOG: false
Checkbox is not selected
Hope this answers your question.

Categories

Resources