Get and set preference values - java

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

Related

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

How to create a Listener to Preferences changes in Preferences activity?

I have Preferences activity in my app that has ListPreference so the user can choose language for the app.
The app displays the new language just after the user close the Preferences activity.
I want to create a listener to the ListPreference so the app will restart when the Listener is triggers (just after the user choose a language/choose item from the ListPreference).
How can I do that?
SettingsActivity:
public class SettingsActivity extends AppCompatPreferenceActivity {
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* #see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setTitle(R.string.action_settings);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
#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);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference(getString(R.string.language_shared_pref_key)));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().finish();
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
pref_general.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:defaultValue="#string/language_code"
android:entries="#array/pref_languages_list_titles"
android:entryValues="#array/pref_languages_list_values"
android:key="#string/language_shared_pref_key"
android:negativeButtonText="#null"
android:positiveButtonText="#null"
android:title="#string/pref_title_language" />
</PreferenceScreen>
Thank you!!!
Here is some real quick sample code for a shared prefs chaneg listener I have set-up in one of my projects; it's located in the onCreate of a Service but obviously can detect changes to my shared prefs that originate from anywhere in my app.
private SharedPreferences.OnSharedPreferenceChangeListener listener;
//Loads Shared preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Setup a shared preference listener for hpwAddress and restart transport
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(/*key for shared pref you're listening for*/) {
//Do stuff; restart activity in your case
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
One possible solution is to keep everything together, and implement the OnSharedPreferenceChangeListener interface inside your own GeneralPreferenceFragment.
You can do that by declaring that GeneralPreferenceFragment both inherits from PreferenceFragment, and implements SharedPreferences.OnSharedPreferenceChangeListener interface. This means that you need to define override for onSharedPreferenceChanged in GeneralPreferenceFragment.
Because preferences can change only if the fragment in question is active, you can register your fragment as listener in onResume for a fragment (via registerOnSharedPreferenceChangeListener), and unregister it on onStop.
The following example code is in Kotlin, not in Java, but it should be fairly easy to translate it.
class SettingsActivity : AppCompatActivity() {
// ...
class SettingsFragment : PreferenceFragmentCompat(),
SharedPreferences.OnSharedPreferenceChangeListener
{
// ...
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?,
key: String?) {
if (key == "<something>")
// do something
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences
?.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences
?.unregisterOnSharedPreferenceChangeListener(this)
}
}

Persisting programmatically added preferences in android

basically what I want is this:
-> I have some settings that (of course) can be modified by the user, on of it is the 'number of cubes'
-> There is an other setting which depends on this setting (movement)
----> if there is one cube the setting is disabled (this works)
----> if there are two cubes there are two options for movement and the setting is enabled (this works too)
----> if there are four cubes there needs to be a choice added for movement and here lays my problem:
I can programmatically change the value of the ListPreference to add this setting but:
-> when the user sets the added value "paired"
and
-> (s)he moves away from the settings, the setting is read correctly
however
-> when the users moves back to the settings the setting is set to the first element of the list(synchronized), not being the choice (s)he made earlier
-> the setting (paired) is remembered by the SharedPreferences instance which I get by calling:
PreferenceManager.getDefaultSharedPreferences(context);
but when moving to the settings again shows the wrong value for the setting (which nobody wants)
How do I persist a programmatically added value?
Of course the reason is that I read the preferences.xml again when the Activity is resumed, but I don't know how to persist the choice made by the user when the Activity is recreated.
This is my code: (the two methods that matter)
public class SettingsActivity extends PreferenceActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d("SA", "onCreate");
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
updateLists();
}
private void updateLists() {
Log.d("SA", "updateLists");
Preference numberOfCubesPref = findPreference("numberOfCubes");
Preference tupleTypePref = findPreference("tuple");
Preference movementTypePref = findPreference("movement_type");
Preference pictureDistributionPref = findPreference("distribution_of_pictures");
ListPreference numberOfCubesListPref = (ListPreference) numberOfCubesPref;
if(numberOfCubesListPref.getEntry() == null){
numberOfCubesListPref.setValueIndex(0);
}
numberOfCubesPref.setSummary(numberOfCubesListPref.getEntry());
ListPreference movementTypeListPref = (ListPreference) movementTypePref;
if(movementTypeListPref.getEntry() == null){
movementTypeListPref.setValueIndex(0);
}
if (numberOfCubesListPref.getEntry().equals("Four")) {
movementTypePref.setEnabled(true);
pictureDistributionPref.setEnabled(true);
CharSequence[] oldEntries = movementTypeListPref.getEntries();
if (oldEntries.length == 2) {
Log.d("SA","length is twoo");
CharSequence[] newEntries = new CharSequence[oldEntries.length + 1];
newEntries[0] = oldEntries[0];
newEntries[1] = "Paired";
newEntries[2] = oldEntries[1];
movementTypeListPref.setEntries(newEntries);
CharSequence[] oldEntryValues = movementTypeListPref
.getEntryValues();
CharSequence[] newEntryValues = new CharSequence[oldEntryValues.length + 1];
newEntryValues[0] = oldEntryValues[0];
newEntryValues[1] = "Paired";
newEntryValues[2] = oldEntryValues[1];
movementTypeListPref.setEntryValues(newEntryValues);
}
} else if (numberOfCubesListPref.getEntry().equals("Two")) {
movementTypePref.setEnabled(true);
pictureDistributionPref.setEnabled(true);
CharSequence[] oldEntries = movementTypeListPref.getEntries();
if (oldEntries.length == 3) {
CharSequence[] newEntries = new CharSequence[oldEntries.length - 1];
newEntries[0] = oldEntries[0];
newEntries[1] = oldEntries[2];
movementTypeListPref.setEntries(newEntries);
CharSequence[] oldEntryValues = movementTypeListPref
.getEntryValues();
CharSequence[] newEntryValues = new CharSequence[oldEntryValues.length - 1];
newEntryValues[0] = oldEntryValues[0];
newEntryValues[1] = oldEntryValues[2];
movementTypeListPref.setEntryValues(newEntryValues);
}
} else {
movementTypePref.setEnabled(false);
pictureDistributionPref.setEnabled(false);
}
ListPreference pictureDistributionListPref = (ListPreference) pictureDistributionPref;
ListPreference tupleTypeListPref = (ListPreference) tupleTypePref;
if(tupleTypeListPref.getEntry() == null){
tupleTypeListPref.setValueIndex(0);
}
CharSequence[] entries = pictureDistributionListPref.getEntries();
CharSequence target, replacement;
if (tupleTypeListPref.getEntry().equals("Two of the same kind")) {
target = "Triplet";
replacement = "Pair";
} else {
target = "Pair";
replacement = "Triplet";
}
for (int i = 0; i < entries.length; i++) {
entries[i] = ((String) entries[i]).replace(target, replacement);
}
pictureDistributionListPref.setEntries(entries);
if(pictureDistributionListPref.getEntry() == null){
pictureDistributionListPref.setValueIndex(0);
}
tupleTypePref.setSummary(tupleTypeListPref.getEntry());
movementTypePref.setSummary(movementTypeListPref.getEntry());
pictureDistributionPref.setSummary(pictureDistributionListPref.getEntry());
}
and my preferences.xml (relevant piece):
<ListPreference
android:dialogTitle="#string/choose_movement_type"
android:enabled="false"
android:entries="#array/movement_type_entries"
android:entryValues="#array/movement_type_values"
android:key="movement_type"
android:title="#string/movement_type" />
and strings.xml: (relevant piece)
<string name="movement_type">Movement type</string>
<string name="choose_movement_type">How do you want to control the cubes?</string>
<string-array name="movement_type_entries">
<item>Synchronized</item>
<item>Independent</item>
</string-array>
<string-array name="movement_type_values">
<item>Synchronized</item>
<item>Independent</item>
</string-array>
The activity is called from within an other activity like this:
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this,
SettingsActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
any help/comments/tips are welcome :)
S.
it looks like you are modifying the preference temporary. to save the prefrences and be sure it remains the same, use sharedPreferencesTurbo

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.

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

Categories