Android Checkbox preference - android

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.

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

Boolean Shared Preference is not storing

I am working on an Android game, in which in settings there is an option to turn off/on the sound of game.
I want to store these settings for the game, for this i am using shared preference to store a boolean value.
but issue is Boolean variable is not saving after app is closed.
here is my Code
Button Click Listener which is setting the SharedPreference
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check == false) {
check = true;
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF, Constants.FIRSTTIME, true);
volume.setBackgroundResource(R.drawable.mute);
Log.e("Check is True", "Preference is True");
} else if (check == true) {
check = false;
volume.setBackgroundResource(R.drawable.volume);
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF,Constants.FIRSTTIME, false);
Log.e("Check is false", "Preference is false");
}
Toast.makeText(getApplicationContext(), "Volume is Clicked",
Toast.LENGTH_SHORT).show();
}
});
My function to set the boolean SharedPreference
public static final void setBoolPreference(Context base, String prefName,
String key, boolean value) {
SharedPreferences userPref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userPref.edit();
editor.putBoolean(key, value);
editor.commit();
}
This is how i am getting the SharedPreference
public static final boolean getBoolPreference(Context base,
String prefName, String key) {
SharedPreferences usePref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
boolean value = usePref.getBoolean(key, false);
return value;
}
and this is the code where i need to use the sharedpreference saved state to play sound or not
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.stronghold);
if (PrefrencesClass.getBoolPreference(context, Constants.APPSPREF,
Constants.FIRSTTIME) == false) {
mPlayer.start();
mPlayer.setLooping(true);
}
Boolean state is not saving Please Help
Try this
public static void saveBooleanToSharedPref(Context context, String key, boolean value){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.commit();
}//saveBooleanToSharedPref
public static boolean getBooleanBySharedPref(Context context, String key){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean value = settings.getBoolean(key, true);
return value;
}//getStringBySharedPref
Your set is wrong, because you use putInt method.
You should be able to say:
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = !check // avoids if statements, same below
SharedPreferences prefsget = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor prefset = prefsget.edit();
prefset.putBoolean(yourBoolVar, !prefsget.getBoolean(yourBoolVar, false));
prefset.commit();
}
});
You can still put an if statement for setting image background. But the what I have above should cut down on a lot of your code. Remember to replace the activity I typed above with your own activity and also for the boolean variable too.

Android-One clicklistener for many CheckBoxPreference

I have some CheckBoxPreference elements for which I would like to use one onClickListener for all the CheckBoxPreference in my page. Here is what I'm trying to do:
CheckBoxPreference checkboxPref = (CheckBoxPreference)getPreferenceManager().findPreference("preference1");
CheckBoxPreference checkboxPref1 = (CheckBoxPreference)getPreferenceManager().findPreference("preference2");
checkboxPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
CheckBoxPreference pref = (CheckBoxPreference) findPreference("preference1");
if (pref.isChecked())
{
pref.setChecked(false);
dialog.show();
}else if (!pref.isChecked())
{
pref.setChecked(true);
dialog.show();
}
return false;
}
});
}
How can i make this onPreferenceClick() be executed for the checkboxPref1?
Any ideas? Thanks!
OnePreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
CheckBoxPreference pref = (CheckBoxPreference) findPreference("preference1");
pref.setChecked(!pref.isChecked());
dialog.show();
return false;
}
});
checkboxPref.setOnPreferenceClickListener(listener);
checkboxPref1.setOnPreferenceClickListener(listener);
Alternatively you can have your class implement the interface and then just pass this to both checkbox preferences.
To add onto Bens Answer, it is best practice to create the Listener as private final (or public final if it needs to be accessed elsewhere) since it will not change:
private final OnePreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
CheckBoxPreference pref = (CheckBoxPreference) findPreference("preference1");
if (pref.isChecked()) {
pref.setChecked(false);
dialog.show();
}else if (!pref.isChecked()){
pref.setChecked(true);
dialog.show();
}
return false;
}
});
If the Class itself is pretty simple then you can add implements Preference.OnPreferenceClickListener to your class which will force you to add Override:
#Override
public boolean onPreferenceClick(Preference preference) {
CheckBoxPreference pref = (CheckBoxPreference) findPreference("preference1");
if (pref.isChecked()) {
pref.setChecked(false);
dialog.show();
}else if (!pref.isChecked()){
pref.setChecked(true);
dialog.show();
}
return false;
}
#Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
CheckBoxPreference pref = (CheckBoxPreference) findPreference("preference1");
if (pref.isChecked())
{
pref.setChecked(true);
}else if (!pref.isChecked())
{
pref.setChecked(false);
}
return pref.isChecked();
}

Setting CheckBoxPreference from SharedPreference

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);
}
}

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();
}
}
});

Categories

Resources