I believe I am correctly initializing preferences from XML. My Preferences Screen also works properly and reflects the correct user selected settings.
However, upon first invocation of that Preferences Screen, none of the settings are checked (checkbox) or selected (list). This, of course, confuses the user as it doesn't reflect the current (default/initial) value.
Since all I do to invoke the Preferences Screen is
startActivity(new Intent(this, EditPreferences.class));
And my EditPreferences class only contains:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.usersettings);
}
I am not sure where or how to tell it to pre-initialize the visual display with the default setting.
I have this hunch that all I am missing is a single line somewhere, but I don't know where: XML file? override a method in EditPreferences? Other?
Can't you define the default value in the XML itself?
<CheckBoxPreference ...
android:defaultValue="true"
... />
You can specify a default value on a preference (in your xml layout for example):
<EditTextPreference android:defaultValue="whatever" />
Related
I am just trying to change the value of a Preference when the PreferenceActivity has been opened. As there is no "setValue" or similar on a Preference, I try
My code:
long value = System.currentTimeMillis()/1000;
PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putString("test",""+value).apply();
getPreferenceScreen().findPreference("test").setSummary(""+value);
My XML:
<EditTextPreference
android:key="test" />
What I expect:
When clicking on my Preference, it should display the value of time (same than summary) and let me edit it.
What happen:
The value is only changed after I closed the Activity. Next time I open the screen, the value is correct (but as in fact already changed to the next one)
First attempt:
Let s say value is 1521143527. Correctly written in the summary, but when I click on the Preference, the popup display an empty value.
Second attemp:
Summary has changed to 1521143540. When I click on Preference, I can edit the previous value (1521143527)
Third attempt:
New Summary, but Preference value is not changed and is still: 1521143540
etc...
Any idea what is wrong?
DIRTY WORKAROUND:
setPreferenceScreen(null);
addPreferencesFromResource(R.xml.preferences);
Will now force the preference to update, but that's really dirty, and I still don't understand...
If you look into the PreferenceFragment source code ,you can see that there is a method called bindPreferences() which binds the preference values to Views . Only in 2 scenarios this method is called,
When Activity created onActivityCreated(#Nullable Bundle savedInstanceState)
When addPreferencesFromResource() called. there is a handler which triggers the bindPreferences()
Other than this there is no way the views are updated. bindPreferences() is a private method , so you can't call this method outside of the class. So you should update your preferences before either those events.
You mentioned, As a workaround solution, you should update your preference first then call addPreferencesFromResource() . Like below
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long value = System.currentTimeMillis()/1000;
getPreferenceManager().getSharedPreferences().edit().putString("test",""+value).commit();
addPreferencesFromResource(R.xml.pref_general);
getPreferenceScreen().findPreference("test").setSummary(""+value);
}
I'm trying to create a very basic preferences activity, extending PreferenceActivity. In the documentation, I read:
The PreferenceActivity automatically persists the settings associated with each Preference when the user makes a change.
However, when I:
Change a setting (any setting)
Close the app
Remove the app from the recently used list
Relaunch the app
The setting is reset to the default value, which seems to conflict the quoted documentation above. Do I misunderstand something here, is the template faulty, or do I perhaps need additional permissions or other settings to use the PreferenceActivity auto-persist feature?
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment()).commit();
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
And preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="pref_language_reading"
android:title="#string/pref_title_language_dailyreading"
android:entries="#array/pref_languages_dailyreading_entries"
android:entryValues="#array/pref_languages_dailyreading_values"
android:defaultValue="#string/pref_language_dailyreading_default"
android:persistent="true" />
</PreferenceScreen>
The strings and arrays exist, and I can select a language properly. The setting is saved when I go to another activity, and then back. But closing the app and relaunching discards the saved value.
When I read out the SharedPreference corresponding to this preference (before relaunching), I see the correct setting. After relaunching, the SharedPreference does not exist anymore though.
The code should work. There is likely something else in your code that causes this behaviour.
In my specific case, it turned out there was a line
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
In the onCreate() method of the main Activity, causing the SharedPreferences to clear on every launch of the app.
I've created a new settings activity using the wizard in Eclipse. I would like to know how to access the value that reflects the user's choices. In particular, a checkbox option.
The code it has produced is as follows:
/src/com/example/myapp/SettingsActivity.java:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
private void setupSimplePreferencesScreen() {
addPreferencesFromResource(R.xml.pref_general);
//...
}
res/xml/pref_general.xml:
<CheckBoxPreference
android:defaultValue="true"
android:key="example_checkbox"
android:summary="#string/pref_description_social_recommendations"
android:title="#string/pref_title_social_recommendations" />
The wizard creates quite a large example, so I'm not sure if I've copied/pasted all the relevant code, but I have spent quite a long time and I'm pretty sure this is about it, (besides the string xml file).
How can I access the checkbox's value from another activity? I'm guessing I need to use a SharedPreferences object, but I don't know what keys I would use to access the data, as I can't find any constants in the code for that? Thanks
PreferenceManager.getDefaultSharedPreferences(context).
getBoolean(example_checkbox, defaultValue);
The key you use is the one you sepcified in the android:key field
I have a preferences page which is defined by XML - including some default values. I use a PreferenceActivity to display and handle this page. Whenever I use this page to set the preferences the preference file on the file system is updated properly - I can see this via adb.
However, whenever I go back to the settings page after have changed some of the settings, it's the defaults that are shown. Worse than that, if I press back without changing any settings, it then sets the, all back to the default.
Any ideas on how I can get the prefs to actually show the current settings?
My PreferenceActivityis created thus:
#Override
protected void onCreate(Bundle savedInstanceState) {
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
setDefaults(this);
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
The XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:id="#+id/numberOfYearsList"
android:key="numberOfYears"
android:title="Number of Years to Read the Bible"
android:summary="How many years would you like to take to read through the reading plan?"
android:entries="#array/numberOfYears"
android:entryValues="#array/numberOfYears"
android:dialogTitle="How Many Years?"
android:defaultValue="1"
/>
<CheckBoxPreference android:key="ignoreDates"
android:id="#+id/ignoreDatesCheckbox"
android:title="Ignore Dates"
android:summary="Would you like to use the dates in the plan?"
android:defaultValue="false"
/>
</PreferenceScreen>
Nevermind - I did a mistake. As you can see from above, when creating the Preference Activity I'm making a call to a method that sets all the prefs to defaults... Duh!
I'm currently writing a live wallpaper for Android and it has a PreferenceScreen which currently contains only one preference - a DialogPreference to set various properties of animation.
User workflow to configure it currently looks like this:
Settings... => (shows the preferences list with only one title ) Animation speed => MyDialogPreference
What I want is to make the workflow like this:
Settings... => MyDialogPreference
I.e. I'm looking for a way to skip showing that preferences list with only one item and to show that dialog right away.
But it seems that PreferenceActivity requests itself to have PreferenceScreen as a root element of preference hierarchy. So... is it even possible to do what i want? :)
Code references:
Activity code:
public class ForestLakePreferences extends PreferenceActivity
{
protected void onCreate(Bundle savedState)
{
super.onCreate(savedState);
getPreferenceManager().setSharedPreferencesName(
ForestLakeWallpaper.PREFS_NAME);
addPreferencesFromResource(R.xml.preferences);
}
}
Prefs resource:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="lake_preferences">
<DurationEditDialog
android:title="#string/prefs_duration_title"
android:dialogTitle="#string/configure_durations_dlg_title"
android:dialogLayout="#xml/set_durations_layout" />
</PreferenceScreen>
It turned out this can't be done in that way.
But i've found a workaround: i made my activity not a PreferencesActivity, but a custom one and made it look like dialog by placing the following in AndroidManifest.xml
<activity android:theme="#android:style/Theme.Dialog" .... />
A DialogPreference has a showDialog(Bundle state) method, try calling it. I am not sure if you will have to give it anything else like the Preferences or anything.