MultiSelectListPreference not storing values? - android

I'm rather new to Android App developing so maybe I'm just making a simple newbie mistake, but here's my problem:
I have 2 simple Activities, MainActivity and SettingsActivity. In MainActivity I have a button which displays SettingsActivity. Within SettingsActivity I include a PreferenceFragment SettingsFragment and display a ButtonBar at the bottom of the Activity. Within the SettingsFragment I have a MultiSelectListPreference defined as follows:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/title_schedule_settings">
<MultiSelectListPreference
android:key="#string/key_list_schedule"
android:title="#string/title_schedule_list"
android:dialogTitle="#string/title_schedule_list"
android:entries="#array/list_weekdays"
android:entryValues="#array/list_weekdays"
android:defaultValue="#array/empty_list"
android:persistent="true"/>
</PreferenceCategory>
</PreferenceScreen>
Now when I select that Preference it shows me the list with all the entries as defined in the array, I can select multiple entries and when I confirm the dialog the values are in fact stored in the SharedPreferences under the defined key. But if I now show the Preference again it will show me previously selected items as selected, but the values are no longer stored within the SharedPreferences, and after some fiddling around I had to realize that the values in the SharedPreferences apparently get wiped as soon as the dialog is shown.
So now my questions are: is this normal/intended behavior or is this a bug? And how can I work around this?
I already tried making my own implementation of MultiSelectListPreference and override the onPrepareDialogBuilder method like this
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder)
{
super.onPrepareDialogBuilder(builder);
Log.i("mmslp", Arrays.deepToString(PreferenceManager.getDefaultSharedPreferences(getContext()).getStringSet(getKey(), new HashSet<String>()).toArray()));
setValues(PreferenceManager.getDefaultSharedPreferences(getContext()).getStringSet(getKey(), new HashSet<String>()));
}
but the values are apparently wiped already at this point.

I spent some time yesterday on this and am now convinced that it is not intended like that, but actually broken - someone confused reference by pointer and by value. ;-)
Seems to be fixed in the more current versions of Android (since 4.1) though:
https://code.google.com/p/android/issues/detail?id=22807
The way I solved it now for the previous versions of Android is to override the setValues method in my implementation of MultiSelectListPreference and just copy the values into a new object:
#Override
public void setValues( Set<String> values ) {
//Workaround for https://code.google.com/p/android/issues/detail?id=22807
final Set<String> newValues = new HashSet<String>();
newValues.addAll( values );
super.setValues( newValues );
}

Related

DialogPreference is not saving the preference when I expect it to?

I have written a bare bones standard DialogPreference which is working fine, except that it is not saving the preference to default shared preferences when I expected it to.
1) open the app, and main activity shows value of foo from default shared preferences = 1
2) go to settings
3) click on foo setting which opens my DialogPreference and shows value = 1
4) enter value 3
5) close my DialogPreference using Ok button
***** default shared preferences foo should now be 3
6) click on foo setting which opens my DialogPreference and shows value = 1
***** so my DialogPreference didn't save the preference to default shared preferences?
7) cancel dialog
8) go back to main activity which shows value of foo from default shared preferences = 3
***** so my DialogPreference did save the preference to default shared preferences
9) go to settings
10) click on foo setting which opens my DialogPreference and shows value of 3
Why isn't the value of default shared preferences foo = 3 at step (6)?
It seems that the preference is only being saved to default shared preferences when the flow returns to the main activity from the settings list, which is counter intuitive to saving the preference in the onDialogClosed method of DialogPreference.
MyDialogPreference
public class MyDialogPreference extends DialogPreference
{
private static final String DEFAULT_VALUE = "0";
private String value = DEFAULT_VALUE;
private EditText editText;
public MyDialogPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
setDialogLayoutResource(R.layout.constrained_integer_preference);
}
#Override
public void onBindDialogView(View view)
{
super.onBindDialogView(view);
editText = (EditText) view.findViewById(R.id.edit);
editText.setText("" + value);
}
#Override
protected void onDialogClosed(boolean positiveResult)
{
if (positiveResult)
{
persistString(editText.getText().toString());
}
super.onDialogClosed(positiveResult);
}
#Override
protected Object onGetDefaultValue(TypedArray typedArray, int index)
{
return typedArray.getString(index);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue)
{
if (restorePersistedValue)
{
value = getPersistedString(DEFAULT_VALUE);
}
else
{
value = (String) defaultValue;
if (shouldPersist())
{
persistString(value);
}
}
}
}
EDIT: So it appears that the preference I am handling with my DialogPreference has no key, which is causing all the problems. But I have specified the key in the preferences.xml file for this DialogPreference. I have tried everything to force the key to be recognised but nothing is working.
Can anyone tell me how I get a DialogPreference to receive the android:key from the preferences.xml file to work?
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<org.mycompany.myproject.MyDialogPreference
android:defaultValue="11"
android:dialogLayout="#layout/my_preference"
android:inputType="number"
android:key="MY_KEY"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="summary"
android:title="My Preference" />
</PreferenceScreen>
You'd have to implement the OnPreferenceChangeListener and/or call to notifyChanged().
Unless you'd provide the code of that DialogPreference, it's difficult to reproduce the issue.
At some point I always feel like I'm hacking Android, and this is definitely a hack.
Initially I thought the problem I was fighting was that the framework ignores my android:key, because getKey() returns an empty string, but that can't be true because it gets the persistent value when it starts the PreferenceScreen, and saves my changed values to shared preferences when I close the DialogPreference.
So it seems the problem I am fighting is that the framework reads the preferences persistent values in to internal members, and then uses the internal members until the flow returns out of the preferences framework, without refreshing them after a DialogPreference has closed.
But I have finally found a way of getting the PreferenceScreen to refresh the preferences persistent values it holds in it's internal members. Although it's not really a refresh, it's a hack.
So what I do is basically throw away the PreferenceScreen and create a new one. I do this by adding the following code to my SettingsFragment.onCreate method directly before addPreferencesFromResource(R.xml.preferences).
SharedPreferences.OnSharedPreferenceChangeListener prefListener = (prefs, key) ->
{
setPreferenceScreen(null);
addPreferencesFromResource(R.xml.preferences);
};
PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).registerOnSharedPreferenceChangeListener(prefListener);
This is probably bad. I have tested it, repeatedly, though not thouroghly, and have not witnessed any adverse effects so far.
So with this hack, I can now repeatedly open a DialogPreference from the PreferenceScreen, save a new value, then go back in to the DialogPreference with the previously updated value.
I don't believe my hack is the intended way of achieving this outcome, but after days of searching the source code and google for answers, I have not found anything else.
I am leaving this answer here for anyone else that faces the same problem and is brave enough to try my hack. I'll update the answer if (and probably when) I find any problems with the hack.
Better yet, if anyone else can provide a preferred solution, pointing out what I have done wrong that caused the problem, please do.
EDIT: After working for so long, that hack eventually broke, and consistently.
But while removing the hack, I approached the problem with a fresh mind, and using the fact that I determined the dialog is getting the preference key, I used this fix for the problem, which is working perfectly.
I added this line of code to the start of onBindDialogView
value = getSharedPreferences().getString(getKey(), "-1");
Which makes the calls to onGetDefaultValue and onSetInitialValue redundant, but they just don't work as intended, at least not for me.
EDIT:
omg, I hate this!
I did not notice that during an earlier refactor the line of code that updates the DialogPreference internal value in onDialogClosed was removed.
It's usually something simple, and with everything else I was checking, I missed that small change.
I only just noticed it during a code review on the repo, and now I feel silly. So no additional code was required in the end.

Leaving PreferenceActivity, calling Activity still reads old preference?

I feel I'm missing something obvious, but search took me to several different hits, all of which don't directly access my odd issue.
Have an app with a main activity and a preference activity. Add to that a 'preference' class, which simplifies reading and setting preferences. The main activity has an option menu to get to the preference activity:
Preferences class (included for relevance, same thing happens if I don't use this class to read settings).
public class Preferences
{
public static SharedPreferences getPrefs(Context context)
{
SharedPreferences retCont = PreferenceManager.getDefaultSharedPreferences(context);
return retCont;
}
/* Map Page: Show Satellite */
public static boolean getMapShowSatellite(Context context)
{
return Preferences.getPrefs(context).getBoolean(Preferences.getString(context, R.string.option_showSatellite), false);
}
public static void setMapShowSatellite(Context context, boolean newValue)
{
Editor prefsEditor = Preferences.getPrefs(context).edit();
prefsEditor.putBoolean(Preferences.getString(context, R.string.option_showSatellite), newValue);
prefsEditor.commit();
}
}
PreferencesActivity:
public class AppSettings extends PreferenceActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_preferences);
ListPreference stationType = (ListPreference)this.findPreference(this.getString(R.string.option_filterStationType));
stationType.setOnPreferenceChangeListener(this.stationOrderEnable());
}
[...]
}
The last two lines hook up an event to enable/disable other preferences based on one's selection. That works, as expected.
The simple main activity, and related functions:
public class MainMapScreen extends MapActivity
{
private void launchSettings()
{
Intent prefsIntent = new Intent(this.getApplicationContext(), AppSettings.class);
this.startActivity(prefsIntent);
}
#Override
protected void onResume()
{
super.onResume();
Preferences.getMapShowSatellite(); // <-- Returns previous value.
// Re-start the MyLocation Layer from tracking.
this._mapView.requestLayout();
}
[...]
}
Okay, so what happens is, let's say we run the app. At app load, the getMapShowSatellite() returns True. Go into the PreferenceActivity, and change that option to False. Exit the PreferenceActivity by hitting the Back button. At this time, the main activity's onResume() is called. Getting the getMapShowSatellite() at this point returns the previous setting of True. Exiting and relaunching the app will then finally return the False expected.
I'm not calling .commit() manually - and don't think I need to, sicne the setting IS saving, I'm just not getting update values.
What'm I missing? :)
--Fox.
Edit 2: Small update. I thought the issue may be the static calls - so temporarily I changed over my Preferences class (above) to be a instantiated class, no more static. I also added the following code to my onResume() call in the main activity:
//Try reloading preferences?
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String test = sp.getString(Preferences.OPTION_FILTERSTATIONTYPE, "---");
Log.e("BMMaps", test);
What is logged at this point, from leaving the PreferenceActivity, is the old setting. Manually reading the preferences file shows me that the .xml file is getting updated with the user's new setting.
Since it's not obvious, I am hooked into Google's Maps API. Because of this, I had to specify two ifferent processes - one for the Main activity (this one) and another for an activity not related to this issue. All other activities, including the PreferencesActivity have no specified android:process="" in their definition.
Edit 3:
As requested, here's the data preferences file:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="com.tsqmadness.bmmaps.filterStationType">V-?</string>
<boolean name="com.tsqmadness.bmmaps.deviceHasLocation" value="false" />
</map>
And here is the Preference storage XML file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Map Options">
<CheckBoxPreference android:key="com.tsqmadness.bmmaps.mapShowSatellite" android:order="1" android:summary="Whether or not to show satellite imagery on the map." android:summaryOff="Standard road map will be shown." android:summaryOn="Satellite imagery will be show." android:title="Show Satellite Layer?" />
<CheckBoxPreference android:key="com.tsqmadness.bmmaps.mapShowScale" android:order="2" android:summary="Whether or not to show the distance bar on the map." android:summaryOff="The distance bar will not be shown on the map." android:summaryOn="The distance bar will be shown on the map." android:title="Show Map Scale?" />
<CheckBoxPreference android:defaultValue="false" android:key="com.tsqmadness.bmmaps.useMetric" android:order="3" android:summary="Whether to use Metric os SI values." android:summaryOff="SI units (mi/ft) will be shown." android:summaryOn="Metric units (km/m) will be shown." android:title="Use Metric?" />
<ListPreference android:dialogTitle="Station Load Delay" android:entries="#array/static_listDelayDisplay" android:entryValues="#array/static_listDelayValues" android:key="com.tsqmadness.bmmaps.mapBMDelay" android:negativeButtonText="Cancel" android:order="4" android:positiveButtonText="Save" android:summary="The delay after map panning before staions are loaded." android:title="Delay Before Loading" />
</PreferenceCategory>
<PreferenceCategory android:title="Control Station Filter">
<ListPreference android:dialogTitle="Station Type" android:entries="#array/static_listStationTypeDisplay" android:entryValues="#array/static_listStationTypeValues" android:key="com.tsqmadness.bmmaps.filterStationType" android:negativeButtonText="Cancel" android:positiveButtonText="Save" android:summary="The station type to filter on." android:title="Station Type" android:order="1" />
<ListPreference android:dialogTitle="Select Station Order" android:entries="#array/static_listStationHOrderDisplay" android:entryValues="#array/static_listStationHOrderValues" android:key="com.tsqmadness.bmmaps.filterStationOrder" android:negativeButtonText="Cancel" android:positiveButtonText="Save" android:summary="Station Order to filter by." android:title="Station Order" android:order="2" />
<ListPreference android:dialogTitle="Select Station Stability" android:entries="#array/static_listStationStabilityDisplay" android:entryValues="#array/static_listStationStabilityValues" android:key="com.tsqmadness.bmmaps.filterStationStability" android:negativeButtonText="Cancel" android:positiveButtonText="Save" android:summary="Station stability to filter by." android:title="Station Stability" android:order="3" />
<CheckBoxPreference android:key="com.tsqmadness.bmmaps.filterNonPub" android:summaryOff="Non-Publishable stations will not be shown." android:defaultValue="false" android:summaryOn="Non-Publishable stations will be shown on the map." android:order="4" android:title="Show Non-Publishable" />
</PreferenceCategory>
<Preference android:key="temp" android:title="Test" android:summary="Test Item">
<intent android:targetClass="com.tsqmadness.bmmaps.activities.MainMapScreen" android:targetPackage="com.tsqmadness.bmmaps" />
</Preference>
</PreferenceScreen>
When changing the filterStationType parameter, and hitting the back button out of PreferenceActivity changes the preferences file from the above from V-? to H-?, as it should. However, reading the value from the SharedPreferences on the main activity still gives the V-?, until app restart. Ah, also, I have a OnPreferenceChangeListnener() in the PreferenceActivity, and that is called when the value changes.
Final Edit: Apparently, it's the use of named android:process for the given activity. This is needed for Google maps API to allow two separate MapActivitys in the same app use different settings. If the PreferenceActivity is moved to the same named-process, then the code above, reading the setting in the onResume() returns the correct value.
Since everything checks out, my guess is that you have a typo, or incorrect or undefined, key in your PreferenceActivity's app_preferences.xml file for the key R.string.option_showSatellite (whatever that string is). This would result in two keys with [unbeknownst to you] different names that you think point to the same value. Really, the prefs activity is using one key and your Preference class is using the other -- resulting in two different keys and two different values.
Double check your keys. Make sure you are not also using the literal "R.string.options_showSatellite" as the key in the xml file, but rather, the actual string. If you want to use the localized version then #string/options_showSatellite would work for the key. However, keys need not be localized.
If you're curious, this can be double checked by opening the preference file that is created by the preference manager in your app's data directory in a standard text editor.
onResume you have to get a fresh reference to SharedPreferences, otherwise you're just using an object that is already in memory (and has your old values)
EDIT:
Rather than down-voting answers that you don't understand, why not ask for clarification instead?
What I mean is that you should pull your Prefs the correct way (rather than how you're doing it)...
SharedPreferences sp = getSharedPreferences(getPackageName(), MODE_PRIVATE);
And then see what happens.

Dynamically create CheckBoxPreferences

I am currently building out a list of rows with checkboxes dynamically using content from a web service. However, this ListView will need to do pretty much what a PreferenceActivity would accomplish.
I don't know the number of rows as the content is dynamic so I can't create each CheckBoxPreference in XML. How do I go about building a PreferenceActivity that will display an unknown number rows with a CheckBoxPreference dynamically?
I think you're looking for something like 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);
}
}
Well #Jodes, actually both of you are right, but the correct way of doing this would be using a ListPreference.
I would use a entire programmatic approach, from my experience it's easier to be consistent; either create an entire XML layout via code, or via XML, but mixing the 2 can be weird and you cannot alter everything set via XML...
onCreate(){
this.setPreferenceScreen(createPreferenceHierarchy());
}
public PreferenceScreen createPreferenceHierarchy(){
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
// category 1 created programmatically
PreferenceCategory cat1 = new PreferenceCategory(this);
cat1.setTitle("title");
root.addPreference(cat1);
ListPreference list1 = new ListPreference(this);
list1.setTitle(getResources().getString(R.string.some_string_title));
list1.setSummary(getResources().getString(R.string.some_string_text));
list1.setDialogTitle(getResources().getString(R.string.some_string_pick_title));
list1.setKey("your_key");
CharSequence[] entries = calendars.getCalenders(); //or anything else that returns the right data
list1.setEntries(entries);
int length = entries.length;
CharSequence[] values = new CharSequence[length];
for (int i=0; i<length; i++){
CharSequence val = ""+i+1+"";
values[i] = val;
}
list1.setEntryValues(values);
cat1.addPreference(list1);
return root;
}//end method
However, using this approach you will run into the platform's limitations of not having a multiple select ListPreference, and you'll probably want to implement something else.
I found this solution, which works great. You'll have to read the comments to find clues about how to debug the code though...
You need a ListView for that, a PreferenceActivity. As discussed in this link, PreferenceActivity should only be used for actually saving preferences.
Instead you could either create a simple dialog with single or multiple choice options:
http://developer.android.com/guide/topics/ui/dialogs.html
Or use a ListView as in the API examples Google provides, they give a simple example:
http://hi-android.info/docs/resources/samples/ApiDemos/src/com/example/android/apis/view/List10.html
Use PreferenceFragmentCompat from Preference Compat Library
compile 'com.android.support:preference-v7:23.4.0'
Check this article for the implementation details https://medium.com/#arasthel92/dynamically-creating-preferences-on-android-ecc56e4f0789#.71ssvjses

Android, subclass Preference class

I am tryig to write an Android Honeycomb application and I am having trouble subclassing Preference: http://developer.android.com/reference/android/preference/Preference.html
I want to make a similar layout with title and summary but also a progress bar.
I have created the layout and added the custom preference class but I can't seem to get hold of the instance of it to set the values of the items in it.
It seems that the preference key doesn't work for the custom class.
Here is my preference definition compared to the standard preference class:
<Preference
android:key="int_free_storage"
android:title="Free Space"
android:summary="free storage value here"/>
<com.hamid.storageether.SpacePreference
android:key="int_space_test"
android:title="Test"
android:summary="This is my custom preference"/>
My my preference subclass then sets my XML layout as it's layout resource in its constructor
setLayoutResource(R.layout.space_pref_layout);
it also overrides the setTitle and setSummary methods....
In my main PreferenceActivity I try to get hold of my Preference by it's key but no luck it seems, since the preference never gets updated:
// These Two work
Preference intTotal = (Preference)findPreference("int_total_storage");
Preference intFree = (Preference)findPreference("int_free_storage");
intTotal.setSummary("Standard Preference Summary 1");
intFree.setSummary("Standard Preference Summary 2");
// My subclass doesn't - It just displays the default text defined in the layout xml.
SpacePreference intTest = (SpacePreference)findPreference("int_test_space");
intTest.setTitle("Testtttyyy");
intTest.setSummary("Test Summary");
Could someone please point me towards where I may be going wrong?
Is this code copied straight from the program or retyped? If copied, then your key is "int_space_test" in XML and "int_test_space" in code. It should be throwing a null pointer exception on the next line where you use intTest if that's the case.

Nested preferences.xml

Is it somehow possible to include one preferences.xml into another, like it can be done for layouts with the <include /> tag?
Let's say:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceScreen
android:title="#string/pref_group_title_visual">
<include
preferences_filename="xml/pref_visual"/>
</PreferenceScreen>
...
Solution here it is to inflate both preference files from PreferencesActivity. For example:
addPreferencesFromResource(R.xml.options);
addPreferencesFromResource(R.xml.additional_options);
The solution soul shows works. It can be expanded to only show preferences if you're the developer using an unsigned version of the app ;)
addPreferencesFromResource(R.xml.options);
addPreferencesFromResource(R.xml.additional_options);
if (BuildConfig.DEBUG) {
addPreferencesFromResource(R.xml.developer_options);
}
I created a blog post regarding this issue and have a complete working code example available for download.
http://androidfu.blogspot.com/2012/05/developer-debug-with-nested-preferences.html
To truly achieve the nesting effect you can use this technique to relocate the loaded preferences to a group already loaded.
PreferenceCategory notifications = (PreferenceCategory) getPreferenceScreen ().findPreference (PreferenceKey.pref_notifications.name ());
addPreferencesFromResource (R.xml.pref_notifications, notifications);
Where the enhanced addPreferencesFromResource is defined as:
private void addPreferencesFromResource (int id, PreferenceGroup newParent) {
PreferenceScreen screen = getPreferenceScreen ();
int last = screen.getPreferenceCount ();
addPreferencesFromResource (id);
while (screen.getPreferenceCount () > last) {
Preference p = screen.getPreference (last);
screen.removePreference (p); // decreases the preference count
newParent.addPreference (p);
}
}
It works for any PreferenceGroup such as PreferenceScreen and PreferenceCategory.
No, it seems to be impossible. But there's a simple workaround. You can make another PreferenceActivity that loads nested PreferenceScreen. And in the main preference.xml file you need to create a Preference object and set an Intent object for it in code (using setIntent() method). This Intent must be used to create the second PreferenceActivity.

Categories

Resources