Android: SharedPreference: Defaults not set at startup
Asked Answered
M

4

10

I have Listpreferences in my app. They don't appear to be setting to their defaults right after installation - they appear to be null. I'm trying to figure out why my default preferences are not being set right after installation. In my main code I have:

      SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

      InUnits = sp.getString("List1", "defValue");
       InAngs = sp.getString("List2", "defValue");
       OutUnits = sp.getString("List3", "defValue");
       OutAngs = sp.getString("List4", "defValue");

Right after the above code executes, each variable contains "defValue" instead of the actual values I have assigned in my ListPreference below.

My preference xml file is called, "settings.xml". Here's what one of the ListPreferences there looks like:

       <ListPreference
       android:key="List1"
       android:title="Input: Alph"
       android:summary="Choose Alph or Ralph"
       android:entries="@array/inputAlph"
       android:entryValues="@array/input_Alph_codes"
       android:dialogTitle="Input Alph"
       android:defaultValue="ININ"/>           

Here's what some of my strings.xml file looks like:

<string-array name="inputUnits">
    <item>Alph</item>
    <item>Ralph</item>  
    </string-array>   
    <string-array name="input_Alph_codes">
    <item>ININ</item>
    <item>INMM</item>
    </string-array>

When I go to menu, and then settings, I can see my defaults checked (radiobuttoned). Then when I go back from the settings menu to my main screen - all is well - for life! ...then each var above is assigned the proper default value.

This only happens when I first install my app on the phone. After I go to the settings screen once and then right out of it, the app is fine and accepts any setting changes.

By the way, as you can see, "List1" is the android:key within a file called settings.xml in my res/xml folder.

Machismo answered 1/5, 2010 at 21:0 Comment(2)
One correction above: In my strings.xml example code above, the string-array name should not read "inputUnits" but should have been: <string-array name="inputAlph".Machismo
possible duplicate of Android Preferences: How to load the default values when the user hasn't used the preferences-screen?Garett
L
23

They don't appear to be setting to their defaults right after installation - they appear to be null.

That's what's supposed to happen.

I'm trying to figure out why my default preferences are not being set right after installation.

They're not supposed to be. The preference XML you have listed there is only used for populating a PreferenceActivity, nothing more. Until the user opens the PreferenceActivity, the preferences will be null, and the defaults you supply to the SharedPreferences getters will be returned.


UPDATE

You can use setDefaultValues() on PreferenceManager to assign the defaults from your preference XML to a SharedPreferences. However, be careful of the timing -- this will do disk I/O, and therefore ideally is performed on a background thread.

Lick answered 1/5, 2010 at 21:9 Comment(9)
That really clears up a lot of things for me. You have been very helpful.Machismo
Can I use code to look at those preference defaults and assign them upon initial program startup?Machismo
You could load and walk through the preference XML, if you want. Unless you have a whole bunch of preferences, though, it is probably simpler to go a bit less DRY and have the defaults defined twice: once in the preference XML and once in the getter calls.Lick
Let me know if I'm right in what your thinking: When you say, 'Load and walk through the preference XML'...do you mean that the first thing a user would see after installation is the preference screen? I've set it up to do that and all is well. I just wondered if other apps tend to do that and do you think some users could be confused by that? (it would only happen once after installation). Also, please let me know, what do you mean by 'getter calls'?Machismo
On the first, no, I meant use getResources().getXml() to get at the actual XML (the file with the ListPreference stuff), so you could parse out your android:defaultValue attributes. On the second, a "getter" is a method that begins with get (getString(), getInt(), getFloat(), getBoolean(), getThis(), getThat(), getJiggyWitIt(), getBackToWhereYouOnceBelonged(), etc.).Lick
Hey, thanks CommonsWare - man your a great help! I can get into all the above coding you mentioned but what do ya think about just presenting the user with the preference screen only once right after install? Is that considered some kind of 'bad habit'?Machismo
Well, they might not necessarily understand what you're asking for in the preferences, if they are new to your app.Lick
Great answer CommonsWare - thanks for your help. It'll be nice when I know enough about android and java where I can answer a few of these questions myself. Thanks for being so patient with me. Have a great app...alMachismo
@Mr_and_Mrs_D: I wasn't aware of that method three-plus years ago. Sorry!Lick
E
12

Set the default values to SharedPreferences from your preference XML.

PreferenceManager.setDefaultValues(Context context, int resourceId, boolean readAgain)

PreferenceManager.setDefaultValues

Emmettemmey answered 29/12, 2011 at 15:13 Comment(0)
N
0

One can use the predefined preference-key PreferenceManager.KEY_HAS_SET_DEFAULT_VALUES:

/**
 * Apply default values, as defined in XML.
 * @param resId preference resource.
 */
private void setDefaultValues(@XmlRes int resId) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String name = PreferenceManager.KEY_HAS_SET_DEFAULT_VALUES;
    if (! prefs.getBoolean(name, false)) {
        PreferenceManager.setDefaultValues(this, resId, true);
        Log.d(LOG_TAG, "Preferences default values have been set.");
        prefs.edit().putBoolean(name, true).apply();
    }
}
Noma answered 7/3 at 7:24 Comment(0)
F
-3

You can specify a default value like this

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.getString("thePrefKey", "theDefaultValue");

The android:defaultValue="..." in the "layout" settings.xml is only a visual help for user

Fearfully answered 19/5, 2011 at 19:29 Comment(1)
This is exactly what he is doing already, as I have this exact same questionElboa

© 2022 - 2024 — McMap. All rights reserved.