The value is saved well in SharedPreference when i push it , but it doesn't show when i open another time the PreferenceActivity. It runs if i don't put the android:entryValues , but i can't use it cause there is some difference using distinct languages in order to see what's the value of the prefference.
¿Any idea of what can i do?
Thanks for reading.
code:
the PreferencesMenu activity:
public class PreferencesMenu extends PreferenceActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setDefaultKeyMode(MODE_PRIVATE);
addPreferencesFromResource(R.layout.preferences);
getPreferenceManager().setSharedPreferencesName("Gat_Preferences");
}
}
some of strings.xml:
<string-array name="menu_preference_general_order_array">
<item>Default</item>
<item>Alphabetical</item>
</string-array>
<string-array name="menu_preference_general_order_values">
<item>default</item>
<item>alphabetical</item>
</string-array>
preferences.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
...
<PreferenceCategory android:title="#string/menu_preference_general">
<ListPreference
android:key="list_order"
android:persistent="true"
android:title="#string/menu_preference_general_order_title"
android:summary="#string/menu_preference_general_order_description"
android:entries="#array/menu_preference_general_order_array"
android:entryValues="#array/menu_preference_general_order_values"/>
</PreferenceCategory>
</PreferenceScreen>
mod :
I use android 2.1 , and i can't use the new fragments preference.
You need to tell the preference API what file name you want to use before loading everything up.
Instead of this:
addPreferencesFromResource(R.layout.preferences);
getPreferenceManager().setSharedPreferencesName("Gat_Preferences");
Do this:
getPreferenceManager().setSharedPreferencesName("Gat_Preferences");
addPreferencesFromResource(R.layout.preferences);
On a sidenote, don't use R.layout.preferences. You should use R.xml.preferences, putting the file under /res/xml and not under /res/layout. It does work your way, but it's not guaranteed to work in all API versions, since it's not the default way of working with preferences XML files.
Your preferences.xml should be in res/xml.
Also, you should assign the default value
<ListPreference
android:key="list_order"
android:persistent="true"
android:title="#string/menu_preference_general_order_title"
android:summary="#string/menu_preference_general_order_description"
android:entries="#array/menu_preference_general_order_array"
android:entryValues="#array/menu_preference_general_order_values"
android:defaultValue="default"
/>
Related
I have two roughly connected issues in my new Android app regarding the Settings. The former is the need to retrieve the information from the preferences without displaying the specific setting activity by performing some:
addPreferencesFromResource(R.xml.preferences);
in another activity.
Is it possible to do it or how else may I retrieve the data without displaying the activity, or is it possible to start the activity without displaying it?
The latter more distressing one is that even in the SettingActivity, when I call that function I recently started getting a crash complaining:
java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.String
Like if something internal were set somehow expecting something. What may I do and in particular how may I reset this sort of hidden structure?
This is my xml file: if I just keep the entries in the former category it does not crash, if I add any field in the latter it does:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/switches"
android:key="switches">
<EditTextPreference
android:key="night_switch_start"
android:summary="#string/ext_night_switch_start"
android:defaultValue="22"
android:title="#string/night_switch_start" />
<EditTextPreference
android:key="day_switch_start"
android:summary="#string/ext_day_switch_start"
android:defaultValue="6"
android:title="#string/day_switch_start"/>
</PreferenceCategory>
<PreferenceCategory
android:title="#string/tokens"
android:key="tokens">
<EditTextPreference
android:key="token_day"
android:summary="#string/ext_token_day"
android:defaultValue="3"
android:title="#string/token_day" />
</PreferenceCategory>
</PreferenceScreen>
Thanks, Fabrizio
For you first question, you can retrieve a preference saved in a PreferenceActivity by calling PreferenceManager#getDefaultSharedPreferences(Context). This is a static method, so you can have in your Activity something like:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
About your second question, I'm not sure what is happening. Try cleaning the project before you run it again.
I answer here to be able to show my code better: this is the first summarizing part of the xml file I suspect might have problems:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/switches"
android:key="switches">
<EditTextPreference
android:key="night_switch_start"
android:summary="#string/ext_night_switch_start"
android:defaultValue="22"
android:inputType="numberDecimal"
android:title="#string/night_switch_start" />
<EditTextPreference
android:key="day_switch_start"
android:summary="#string/ext_day_switch_start"
android:defaultValue="6"
android:inputType="numberDecimal"
android:title="#string/day_switch_start"/>
</PreferenceCategory>
<PreferenceCategory
android:title="#string/tokens"
android:key="switches">
<EditTextPreference
android:key="token_day"
android:summary="#string/ext_token_day"
android:defaultValue="3"
android:inputType="numberDecimal"
android:title="#string/token_day" />
</PreferenceCategory>
</PreferenceScreen>
My code is very simple: the crashing setting part is the following.
public class SettingsActivity extends PreferenceActivity {
private static final String LOG_TAG = "preferences";
public static class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
...
}
While the code loading the string and finding "mostly" empty strings is:
sharedPref= PreferenceManager.getDefaultSharedPreferences(Dashboard.dashboard);
startDayTime=Integer.parseInt(sharedPref.getString("day_switch_start", "")); //correct value
startNightTime=Integer.parseInt(sharedPref.getString("night_switch_start", "")); //empty string thereafter rising an exception.
Also, when I tried leaving just the first two EditText, so not to have the crash, the Setting activity had the correct value for day_switch_start and again an empty string in the night_switch_start field.
When I do getAll() I get the correct values:
{start_night_time=6, day_switch_start=6, notifications_new_message_ringtone=content://settings/system/notification_sound, notifications_new_message=true, second_rate_limit=24.0, third_rate_fare=1.6, token_day=6.0, token_night=6.0, night_switch_start=22, token_holiday=6.0, start_day_time=6, start_night_switch=John Smith, example_checkbox=true, example_text=John Smith, notifications_new_message_vibrate=false, example_list=-1, first_rate_fare=1.1, first_rate_limit=11.0, max_speed_for_time=20.0, sync_frequency=180, second_rate_fare=1.3, timed_fares=27.0, cooperative=}
Yet, when I try to get the value of them either with:
startDayTime=Integer.parseInt(sharedPref.getString("night_switch_start", "")); or
startNightTime=sharedPref.getInt("night_switch_start", 0);
I retrieve an empty string in both cases.
Half of the answer: clearing the cache of the phone removes all the funny fields and does not crash any longer the setting activity, nor the loading of its values by:
startNightTime=Integer.parseInt(sharedPref.getString("night_switch_start", ""));
The old form:
startNightTime=sharedPref.getInt("night_switch_start", 0);
still crashes, notwithstanding the values seem numeral. Not a big deal, though.
The unanswered problem is how to load the settings from the xml file without entering the SettingsActivity performing:
addPreferencesFromResource(R.xml.preferences);
Is it possible to run the function from outside that activity or is it possible to start the activity without visualizing it to the user?
I have two preference xml files. The first one (pref2.xml) contains 2 preferences:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="key"
android:title="title"
android:defaultValue="false"
/>
<CheckBoxPreference
android:key="key2"
android:title="title"
android:defaultValue="false"
/>
</PreferenceScreen>
and the other one (pref1.xml) contains 1 preference:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="key"
android:title="title"
android:defaultValue="false"
/>
</PreferenceScreen>
in my preference activity I am trying to change them:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref1);
this.getPreferenceScreen().removeAll();
addPreferencesFromResource(R.xml.pref2);
final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
Log.d("LOG", "size of sharedPreferences"+adapter.getCount()+"(should be 2)");
actually here i get the right output and everything is displayed correctly. But I want to change the displayed preferences concerning one preference. Therefore I implemented the OnSharedPreferenceChangeListener in the preference activity:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
super.onSharedPreferenceChanged(sharedPreferences, key);
//switch the widget type
if (key.equals("key")){
this.getPreferenceScreen().removeAll();
addPreferencesFromResource(R.xml.pref1);
final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
Log.d("LOG", "size of sharedPreferences "+adapter.getCount()+" (should be 1)");
}
}
Well, the pref1 preferences are displayed correctly, but the output of
"size of sharedPreferences 2"
indicated that in the background there are still the old preferences applied. If i iterate over the listAdapter i get also the old preferences.
Any idea how I could solve this?
I found out that the listadapter is some how outdated. If I get the count of items via getPreferenceScreen().getPreferenceCount() I get the right amount. But how do I access these preferences ?
I'm fairly sure that problem lies with your having two preferences with a key of "key" even though they are on different screens. A preference is identified by its key and this needs to be unique to avoid conflicts. The listener only knows which preference is being changed from the key. I would change the keys to have unique values.
EDIT: Well, wasn't right :S
...
Okey, I finally found the solution. After changing the PreferenceScreen I need to bind manually the listView again:
getPreferenceScreen().bind((ListView)findViewById(android.R.id.list));
I'm trying to use preference screen. I'm following all steps from online tutorial (once I couldn't get it working, I found other tutorials, and steps seem to be fine). I get to preferences screen, edit values, return to calling activity (via hardware return button). In DDMS perspective FileExplorer shows package_name_preferences.xml file with preferences that should be stored. It contains:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="false">kg</string>
</map>
while I expect (data line only shown).
<string name="weight">kg</string>
Also, if I go change only 1 preference, the same value changes, not a new row is created. I'm just tempted to write my own preference classes that would store data in files or DB, but I know that preferences should work, it just doesn't save properly my stuff.
Edit
Tutorials used:
Main Tutorial
- Was using this as a base, simplified, as I needed only 3 listPreferences so far.
Another One - Used this one back when first installed android, so referred to this one for its section on preferences
Code: (Screen loads, so I'm not showing Manifest)
public class MyPrefs extends PreferenceActivity {
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
addPreferencesFromResource(R.xml.my_prefs);
}
}
my_prefs.xml
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Value Settings">
<ListPreference android:title="Distance"
android:summary="Metric (Kilometer) vs Imperial (Imperial)"
android:defaultValue="km"
android:key="#+id/distanceMesurement"
android:entries="#array/distance"
android:entryValues="#array/distance_values"/>
<ListPreference android:title="Weight"
android:summary="Metric (Kilogram) vs Imperial (Pound)"
android:defaultValue="kg"
android:key="#+id/weightMesurement"
android:entries="#array/weight"
android:entryValues="#array/weight_values"/>
</PreferenceCategory>
</PreferenceScreen>
calling MyPrefs from MainScreen
Intent i = new Intent(MainScreen.this, MyPrefs.class);
startActivity(i);
arrays.xml
<resources>
<string-array name="weight">
<item name="kg">Kilogram (kg)</item>
<item name="lb">Pound (lb)</item>
</string-array>
<string-array name="weight_values">
<item name="kg">kg</item>
<item name="lb">lb</item>
</string-array>
<string-array name="distance">
<item name="km">Kilometer (km)</item>
<item name="mi">Mile (mi)</item>
</string-array>
<string-array name="distance_values">
<item name="km">km</item>
<item name="mi">mi</item>
</string-array>
</resources>
Your key syntax is invalid. Use:
android:key="weight"
I'm trying to set a defaultValue to a ListPreference item.
Here is an sample of my preference.xml file:
<ListPreference android:key="notification_delay"
android:title="#string/settings_push_delay"
android:entries="#array/settings_push_delay_human_value"
android:entryValues="#array/settings_push_delay_phone_value"
android:defaultValue="????">
</ListPreference>
The two arrays:
<string-array name="settings_push_delay_human_value">
<item>every 5 minutes</item>
<item>every 10 minutes</item>
<item>every 15 minutes</item>
</string-array>
<string-array
name="settings_push_delay_phone_value">
<item>300</item>
<item>600</item>
<item>900</item>
</string-array>
When i go into the preference activity, no item of the ListPreference is selected. I've tried to set an int value like 1 in the "android:defaultValue" fied to select "10 minutes" but it does not work.
<ListPreference android:key="notification_delay"
android:title="#string/settings_push_delay"
android:entries="#array/settings_push_delay_human_value"
android:entryValues="#array/settings_push_delay_phone_value"
android:defaultValue="1">
</ListPreference>
Any Idea?
You need to specify the value. So to get the first entry selected by default specify defaultValue="300" in your example.
Happened to be in same situation. Specifying a consistent default value. But graphically was not selected. I cleared the application data. And then it worked as expected.
So a clear may be useful at dev time when adding new XxxPreference items.
In addition to Sven's answer, you have to call the setDefaultValues() method in the starting activity. This will set once all default values.
public class MainActivity extends Activity {
protected void onCreate(final Bundle savedInstanceState) {
// Set all default values once for this application
// This must be done in the 'Main' first activity
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
...
}
}
If it is a valid value from the list, then re-install the app. It will work.
This question already has answers here:
Android Preferences: How to load the default values when the user hasn't used the preferences-screen?
(6 answers)
Closed 9 years ago.
My problem is that when I start application and user didn't open my PreferenceActivity so when I retrieve them don't get any default values defined in my preference.xml file.
preference.xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="applicationPreference" android:title="#string/config"
>
<ListPreference
android:key="pref1"
android:defaultValue="default"
android:title="Title"
android:summary="Summary"
android:entries="#array/entry_names"
android:entryValues="#array/entry_values"
android:dialogTitle="#string/dialog_title"
/>
</PreferenceScreen>
Snippet from my main Activity (onCreate method):
SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String pref1 = appPreferences.getString("pref1", null);
In result I end up with a null value.
In onCreate() of your main Activity just call the PreferenceManager.setDefaultValues() method.
PreferenceManager.setDefaultValues(this, R.xml.preference, false);
This will read your preference.xml file and set the default values defined there. Setting the readAgain argument to false means this will only set the default values if this method has never been called in the past so you don't need to worry about overriding the user's settings each time your Activity is created.
I'll be brief. :)
strings.xml (actually I have prefs.xml exclusively for preferences):
<string name="pref_mypref_key">mypref</string>
<string name="pref_mypref_default">blah</string>
preferences.xml:
android:key="#string/pref_mypref_key"
android:defaultValue="#string/pref_mypref_default"
MyActivity.java:
String myprefVal = prefs.getString(getString(R.string.pref_mypref_key), getString(R.string.pref_mypref_default));
Your call to getString() has null as the second parameter. Change that to be the default value you want.