Not receiving value from CheckBoxPreference in PreferenceScreen? - java

I'm using Eclipse's default "Settings Screen" Activity, which created a class extending PreferenceScreen. The methods being used to grab values seem strange to me, but I'm working with them. I can get the value of an EditTextPreference this way:
}else if(preference instanceof EditTextPreference) {
preference = (EditTextPreference) preference;
int p_value = Integer.valueOf(((EditTextPreference) preference).getText());
MainActivity.decimals = p_value;
This works fine for the EditTextPreference and ListPreference. However, upon trying it with a CheckBoxPreference, like so:
}else if(preference instanceof CheckBoxPreference) {
preference = (CheckBoxPreference) preference;
boolean toastEn = ((CheckBoxPreference) preference).isChecked();
if(toastEn) {
MainActivity.toastsEnabled = true;
}else MainActivity.toastsEnabled = false;
}
It does not work. From the small amount of debugging I managed to do (Toasts and Logs seem to be very limited in this method), it looks like it's just not getting the value of the CheckBoxPreference.
Am I going about this correctly?
Edit: the encapsulating method looks like this (I forgot to add it at first, sorry, it might be important):
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {

You can try add a listener to the checkbox such as setOnPreferenceChangeListener or setOnPreferenceClickListener

That is really strange Preferences code.
What I did for Preferences was the following:
public class SettingsActivity extends PreferenceActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Where the res\xml\preferences.xml looked like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:defaultValue="true"
android:key="MusicEnabled"
android:title="#string/musicenabled"
/>
<CheckBoxPreference
android:defaultValue="true"
android:key="SoundEnabled"
android:title="#string/soundenabled"
/>
<CheckBoxPreference
android:defaultValue="true"
android:key="IntroEnabled"
android:title="#string/introsoundenabled"
/>
</PreferenceScreen>
And you get its values with the following code:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
soundEnabled = sp.getBoolean("SoundEnabled", false);

Related

MultiSelectPreference onPreferenceChange callback listener isn't called

I am trying to make a MultiSelectPreference. But The list never receives callback listeners when clicking on an item from the list.
XML code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="locale">
<PreferenceCategory android:title="#string/preference_display_category">
<MultiSelectListPreference
android:key="preference_filter_entries"
android:summary="#string/preference_filter_entries_summary"
android:title="#string/preference_filter_entries_title"
android:entries="#array/preference_entry_array"
android:entryValues="#array/preference_filter_entries_array_values"
android:dialogTitle="#string/preference_filter_entries_dialog_title"/>
</PreferenceCategory>
</PreferenceScreen>
Java code:
MultiSelectListPreference multiSelectListPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.fragment_preferences);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
multiSelectListPreference = (MultiSelectListPreference) findPreference("preference_filter_entries");
multiSelectListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Timber.d("onPreferenceChange called %s", "1");
return false;
}
});
}
The above Timber log is never been called when checking on any item from the list!
Change the return to true as follows,
multiSelectListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Timber.d("onPreferenceChange called %s", "1");
return true;
}
});

Get and set preference values

My objective is manage my custom preferences. For this, I have the following code:
MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnTouchListener, GoogleMap.OnInfoWindowClickListener, LocationListener, GoogleMap.OnMapClickListener{
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
launchPreferences(null);
return true;
}
return super.onOptionsItemSelected(item);
}
public void launchPreferences(View view) {
Intent i = new Intent(this, Preferences.class);
startActivity(i);
}
}
Preferences.java
public class Preferences extends PreferenceActivity {
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
updatePreference();
}
settings.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#+id/preferencias_principal" >
<EditTextPreference
android:key="#+id/perimer"
android:title="Perimeter to list"
android:summary="Maximum distance to list"
android:defaultValue="2"/>
<ListPreference
android:key="#+id/leguage"
android:title="Lenguage"
android:summary="What language would you apply?"
android:entries="#array/lenguage"
android:entryValues="#array/lenguageva"
android:defaultValue="1"/>
</PreferenceScreen>
arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="lenguage">
<item>English</item>
<item>Basque</item>
<item>Spanish</item>
</string-array>
<string-array name="lenguageva">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
<string-array name="number">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
<item>11</item>
<item>12</item>
<item>13</item>
<item>14</item>
<item>15</item>
</string-array>
</resources>
I want to get the values of this preference, using this code:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Integer peri = sharedPref.getInt("#+id/perimer", 1);
Integer leng = sharedPref.getInt("#+id/leguage", 2);
But this code return default values, peri=1 and leng=2.
Not only that, sometimes the information added by the preference activity is changed/deleted or in the ListPreference item is not appear the default item selected (as you can be seen in the image).
When I execute the code visible here, with debugger, this is the result:
What can I do?
Thank you!
The main problem is the KEY #+id/perimer and #+id/leguage that you used for your EditTextPreference and ListPreference.
SharedPreferences is unable to recognize it as preference KEY. As you added resource prefix #+id, its treated as int resource id that's why still it works with below lines but doing abnormal behavior and giving you incorrect output.
Integer peri = sharedPref.getInt("#+id/perimer", 1); // WRONG
Integer leng = sharedPref.getInt("#+id/leguage", 2); // WRONG
SOLUTION:
1. Do not use resource prefix #+id with preference KEY. Update your settings.xml as below:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="perimer"
android:title="Perimeter to list"
android:summary="Maximum distance to list"
android:defaultValue="2"/>
<ListPreference
android:key="leguage"
android:title="Lenguage"
android:summary="What language would you apply?"
android:entries="#array/lenguage"
android:entryValues="#array/lenguageva"
android:defaultValue="1"/>
</PreferenceScreen>
2. Get preference values using SharedPreferences.getString(KEY_NAME, DEFAULT_VALUE).
// Get current values
String peri = mSharedPreferences.getString("perimer", "1");
String leng = mSharedPreferences.getString("leguage", "2");
3. Add OnPreferenceChangeListener to your preferences to get the updated values and update the preference summary if needed.
// Required to get the updated value and update summary when you input distance
mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String peri = value.toString();
//Update premier summary
mPreferencePerimer.setSummary(peri);
return true;
}
});
// Required to get the updated value and update summary when you change language from list
mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String leng = value.toString();
int lengIndex = Integer.parseInt(leng) - 1;
// Update leguage summary
mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
return true;
}
});
Here is the full code:
public class Preferences extends PreferenceActivity {
// Preference Keys
public static final String KEY_PREF_PERIMER = "perimer";
public static final String KEY_PREF_LEGUAGE = "leguage";
// Shared preference
SharedPreferences mSharedPreferences;
EditTextPreference mPreferencePerimer;
ListPreference mPreferenceLeguage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
// Shared preference
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
// Perimer
mPreferencePerimer = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_PERIMER);
// Leguage
mPreferenceLeguage = (ListPreference) getPreferenceScreen().findPreference(KEY_PREF_LEGUAGE);
// Get current values
String peri = mSharedPreferences.getString(KEY_PREF_PERIMER, "1");
String leng = mSharedPreferences.getString(KEY_PREF_LEGUAGE, "2");
int lengIndex = Integer.parseInt(leng) - 1;
// Set preference summary
mPreferencePerimer.setSummary(peri);
mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
// Required to get the updated value and update summary when you input distance
mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String peri = value.toString();
//Update premier summary
mPreferencePerimer.setSummary(peri);
return true;
}
});
// Required to get the updated value and update summary when you change language from list
mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String leng = value.toString();
int lengIndex = Integer.parseInt(leng) - 1;
// Update leguage summary
mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
return true;
}
});
}
}
OUTPUT:
DEFAULT STATE
AFTER CHANGE
Hope this will help~
I've done something similar to this and I think this should work. But this code is untested and may throw some error.
public class Preferences extends PreferenceActivity implements android.preference.Preference.OnPreferenceChangeListener {
private ListPreference lang_list;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
// get the stored (or default) value (the index of the selected item)
Integer leng = sharedPref.getInt("#+id/leguage", 2);
// get the reference of the ListPreference defined in settings.xml
lang_list = (ListPreference) getPreferenceManager().findPreference("#+id/leguage");
// set the selected value
lang_list.setValueIndex(leng);
// add a listener to get the changes made by the user. Your Preferences class should implement the OnPreferenceChangeListener interface
lang_list.setOnPreferenceChangeListener(this);
}
...
/// When the user selects an item from the list, this function will be fired
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
// ensure that the change has been in the language list
if (key.equals(lang_list.getKey())) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
// set the value for the key "#+id/leguage"
sharedPref.putInt("#+id/leguage", (int) newValue);
// save the sharedPref object to the file system
sharedPref.apply();
return true;
}
return false;
}
UPDATED 2017/06/09: Your Preferences class must implement the android.preference.Preference.OnPreferenceChangeListener interface in order to work with the line lang_list.setOnPreferenceChangeListener(this);

Android: SharedPreferences not getting updated from PreferenceFragment

I'm posting this question again as I didn't get any answers last time, and I still haven't solved the problem.
I have a settings menu with a PreferenceScreen in which I create a lot of CheckBoxPreferences during runtime (Adding them into the "Exclusion List" prefscreen). I created them no problem, here's the XML code below that it starts with:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceScreen
android:key="exclusion_list_key"
android:title="Exclusion List"
android:persistent="true"
android:summary="" >
</PreferenceScreen>
</PreferenceScreen>
I create the checkboxes in the onCreate method of my PreferenceFragment and add them to the "Exclusion List" PreferenceScreen and that works fine.
I'm trying to set the summary of the "Exclusion List" to be a list of all the checkbox titles that are checked off (so if the checkbox is checked, it's name will be listed in the summary of the "Exclusion List").
In the onCreate() method, the summary gets set properly, there's no problem.
But in the onPreferenceChanged() method, I set the summary of "Exclusion List" to the 'summary' string I built (which contains the correct value), but it doesn't update it! When i press back from my checkbox menu, the "Exclusion List" does not have the updated values.
The last few lines are the ones of interest. I did some printlns to see what's going on:
The listener works fine, runs when expected
My summary var contains what's expected
After calling setSummary(summary), the getSummary() returns the expected value (so that means it got set properly)
However, when I actually press back and see "Exclusion List", it's summary doesn't actually get updated!
Did I miss something? Thanks in advance!
All the code for reference:
public class Settings extends AppCompatActivity {
public static final String EXC_LIST_KEY = "exclusion_list_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
String summary = "";
//Create all the checkboxes inside of the PreferenceScreen
for (int i = 0; i < MainActivity.contactNames.length; i++) {
CheckBoxPreference checkbox = new CheckBoxPreference(getActivity());
checkbox.setTitle(MainActivity.contactNames[i][0]);
checkbox.setKey(MainActivity.contactNames[i][2]);
checkbox.setSummary(MainActivity.contactNames[i][1]);
checkbox.setDefaultValue(false);
((PreferenceScreen) findPreference(EXC_LIST_KEY)).addPreference(checkbox);
if (checkbox.isChecked()) {
summary = summary + checkbox.getTitle() + "\n";
}
}
findPreference(EXC_LIST_KEY).setSummary(summary);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//Checkbox keys all start with 'key_'
if (key.startsWith("key_")) {
String summary = "";
for (int i = 0; i < MainActivity.contactNames.length; i++) {
CheckBoxPreference checkbox = (CheckBoxPreference) findPreference(MainActivity.contactNames[i][2]);
if (checkbox.isChecked()) {
summary = summary + checkbox.getTitle() + "\n";
}
}
System.out.println("Summary I have: " + summary); //Correct summary is printed out
findPreference(EXC_LIST_KEY).setSummary(summary); //Isn't updating the value???
System.out.println("Summary system has: " + findPreference(EXC_LIST_KEY).getSummary()); //Correct summary is printed out
}
}
}
}
try Adding this code in your SettingsFragment
#Override
public void onResume() {
super.onResume();
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
// CHANGE 1: load saved values to set the summaries
onSharedPreferenceChanged(prefs, "exclusion_list_key");
// CHANGE 2: register shared prefs listener in onResume
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
Got it working by adding the following line of code to the end of my onSharedPreferenceChanged() method:
((BaseAdapter)getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();

CheckBoxPreference not ticking when selected in PreferencesActivity

When I click the "Settings" page, my CheckBoxPreference shows exactly how I want it to at this stage, however when I select it, the state does not change (i.e. from Unchecked to Checked).
It seems to be retaining the value of false (default) and still running onPreferenceChanged with false as the value passed. I am running code inside my onPreferenceChangedListener that is dependent on the value of the preference that is changed. As it stands I only have one preference in here.
activity_preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceScreen>
<CheckBoxPreference
android:summaryOn="true"
android:summaryOff="false"
android:key="isReg"
android:title="Receive Push Messages"
android:selectable="true"
android:enabled="true"
android:persistent="true" />
</PreferenceScreen>
</PreferenceScreen>
PrefsActivity.java:
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import com.google.android.gcm.GCMRegistrar;
public class PrefsActivity extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.activity_preferences);
Preference isReg = (Preference) findPreference("isReg");
isReg.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference pref, Object arg1) {
boolean isReg = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isReg", false);
if (isReg){
ServerUtilities.register(getApplicationContext(), GCMRegistrar.getRegistrationId(getApplicationContext()));
}
else {
ServerUtilities.unregister(getApplicationContext(), GCMRegistrar.getRegistrationId(getApplicationContext()));
}
return isReg;
}
});
}
}
You are using the wrong preference widget as per in the code sample,
Preference isReg = (Preference) findPreference("isReg");
It should have been CheckBoxPreference as in
CheckBoxPreference isReg = (CheckBoxPreference) findPreference("isReg");
Edit
One thing I noticed, you're not handling the preference activity properly...consider this code, always, call the preference's commit method in order to save it!
public class PrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
CheckBoxPreference isReg;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.activity_preferences);
PreferenceManager.setDefaultValues(this,R.xml.activity_preferences, false);
isReg = (CheckBoxPreference)findPreference("isReg");
if (isReg != null){
isReg.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
boolean blnIsReg = Boolean.getBoolean(newValue.toString());
Editor e = _prefs.edit();
e.putBoolean("isReg", blnIsReg);
e.commit();
return true;
}
});
}
}
}
#Override
public void onStart(){
super.onStart();
_prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
The listener that is implemented must be in this fashion, which is how the changes are effective:
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(TAG, "onSharedPreferenceChanged; key = " + key);
}
By incorporating the listener, the logcat will show that the preference's key is indeed being changed, i.e. "isReg".
Update the values from the shared preferences in onResume()
method
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(PrefsActivity.this);
boolean isReg = prefs.getBoolean("isReg", false);
Hope Try This it will help You

SharedPreference in android(Tell friend + Disable Dialog notification)

i am developing an android application that has a shared preference, containing :
- Ringtone (done)
disable the dialog notification (alarm, SMS, MMS)(not yet,please read the comment inside the code)
-Tell friend (i am sure my code is right but i am not sure how to put it with Shared preference + i am now sure of place and method that i should put at it- please read to the comment inside the code)
public class Setting extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
String ringtonePreference;
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ringtonePreference = prefs.getString("ringtonePref",
"DEFAULT_RINGTONE_URI");
}
//disable all Notification (Alarm , SMS,MMS)
//what is the method that i should put this code at it? onStart?onDestroy?or what?
SharedPreferences sharedPreferences = this.getPreferences(MODE_PRIVATE);
boolean hideNotification = sharedPreferences.getBoolean("checkbox", false);
if(!hideNotification)
alertDialog.show();
}
//tell friend
//i am not sure if this is right place to this code
//if it is the right place then what is the method that i should put this code at it?onStart?onActivityResult?or what?
SharedPreferences prefs1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
TellFriendPreference = prefs1.getString("tellfriend","null");
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
String str= item.toString();
if(str=="Tell Friends"){
Toast.makeText(this,"First", Toast.LENGTH_LONG).show();
//Go to tell friend activity
//Intent i = new Intent (Help.this, .class);
//startActivity(i);
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "Check out s Application for Android. Download it today from http://s.com");
startActivity(Intent.createChooser(intent, "Tell friends:"));
startActivity(intent);
}
this is prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Second Category" >
<RingtonePreference
android:name="Ringtone Preference"
android:key="ringtonePref"
android:summary="Select a ringtone"
android:title="Ringtones" />
<CheckBoxPreference
android:defaultValue="true"
android:key="checkbox"
android:summary="Check the Box"
android:title="Disable Notification" />
<Preference
android:name="tell Preference"
android:key="tellfriend"
android:summary="if u want to tell ur friends by usinf"
android:title="Tell Friend" />
</PreferenceCategory>
</PreferenceScreen>
please help me, i should submit it after some hours
I solved my problem. I just but tell friend in another activity, my code is correct.

Categories