简体   繁体   中英

Android: Can't load default values from a preferences xml file using sharedpreferences

Trying to load default values from a preference.xml file. and load them using sharedpreferences but the defaultValues from the xml file won´t load for me. Here is my code.

/res/xml/prefs.xml

   <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="prefs" android:title="prefs">
        <Preference android:key="bild" android:title="bild" android:defaultValue="This is bild,0,false"/>
        <Preference android:key="bild2" android:title="bild2" android:defaultValue="This is bild2,1,false"/>
        <Preference android:key="bild3" android:title="bild3" android:defaultValue="This is bild3,2,false"/>
    </PreferenceScreen>

And the Android code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String picture = prefs.getString("bild", "dosen't exist");
    Log.e("test", "This is the picture Value: " + picture);
}

It always prints "dosent't exist", which means in this example that it isen´t loaded correctly?. And can't figure out why it does.

Any help would be appreciated, Thanks

/Eidor

According to this question, your location for a shared preferences file is wrong. Also, if I recall correctly (not feeling too well so may not remember correctly), if you want to read files with key-value pairs you are better off putting them in assets folder and reading from there.

I don't see anything wrong with the preferences being saved in prefs.xml . After recreating your code and slightly modifying it, I got to suspect the plain <Preference>-Tag instead:

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">TestPreference</string>
    <string name="action_settings">Settings</string>

    <string name="pref_header_1">Preference Category</string>

    <string name="pref_default_1">Image 1</string>
    <string name="pref_default_2">Image 2</string>

    <string name="pref_title_1">Title 1</string>
    <string name="pref_title_2">Title 2</string>
    <string name="pref_title_3">Title 3</string>

    <string name="pref_key_1">pref_key_1</string>
    <string name="pref_key_2">pref_key_2</string>
    <string name="pref_key_3">pref_key_3</string>

    <string-array name="pref_entries_3">
        <item>One</item>
        <item>Two</item>
        <item>Five</item>
    </string-array>
    <string-array name="pref_values_3">
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>
</resources>

preference.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="@string/pref_header_1" >
        <Preference
            android:defaultValue="@string/pref_default_1"
            android:key="@string/pref_key_1"
            android:title="@string/pref_title_1" />

        <EditTextPreference
            android:defaultValue="@string/pref_default_2"
            android:key="@string/pref_key_2"
            android:title="@string/pref_title_2" />

        <ListPreference
            android:defaultValue="1"
            android:entries="@array/pref_entries_3"
            android:entryValues="@array/pref_values_3"
            android:key="@string/pref_key_3"
            android:negativeButtonText="@null"
            android:positiveButtonText="@null"
            android:title="@string/pref_title_3" />
    </PreferenceCategory>

</PreferenceScreen>

MainActivity.java

private Logger log = LoggerFactory.getLogger(getClass());

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get default preferences and load default values
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    PreferenceManager.setDefaultValues(this, R.xml.preference, false);

    // Check if keys exist in sharedPreferences
    log.debug("Contains keys #1: {}; #2: {}; #3: {}", new Object[] {
            prefs.contains(getString(R.string.pref_key_1)),
            prefs.contains(getString(R.string.pref_key_2)),
            prefs.contains(getString(R.string.pref_key_3))
    });

    // Get preferences values
    String value1 = prefs.getString(getString(R.string.pref_key_1), "not found");
    String value2 = prefs.getString(getString(R.string.pref_key_2), "not found");
    String value3 = prefs.getString(getString(R.string.pref_key_3), "not found");
    log.debug("Values #1: {}; #2: {}; #3: {}", new Object[] { value1, value2, value3 });

    // prefs.edit().putString(getString(R.string.pref_key_1), getString(R.string.pref_default_1)).apply();
}

Logging result

"Contains keys #1: false; #2: true; #3: true"
"Values #1: not found; #2: Image 2; #3: 1"



Conclusion

If you want a certain preference to be user-editable, you're probably better of using a concrete Preference such as EditTextPreference, ListPreference, CheckboxPreferencete ( check here for a complete list of subclasses that suits your needs.

If for some reason you still want to use plain Preferences, I suppose you have to load them manually like this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString(getString(R.string.pref_key_1), getString(R.string.pref_default_1)).apply();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM