简体   繁体   中英

set shared preference default programmatically

I have a shared preference with no default value defined in the xml because I would like to set the default value programmatically when the main activity is created. The preference in question should either be the device language (if that language is available), otherwise the first available language, where the languages are defined in the appropriate xml as a string array.

I currently have, inside the main activity's onCreate method, the following

    SharedPreferences preferences = getSharedPreferences(
            getString(R.string.shared_prefs_key),
            MODE_PRIVATE
    );

    String detailLanguage = preferences.getString(
            getResources().getString(R.string.detail_display_language),
            ""
    );

    if (detailLanguage.isEmpty()) {
        String deviceLanguage = Locale.getDefault().getLanguage();

        String[] availableLanguages = getResources().getStringArray(R.array.pref_entry_values_detail_display_language);
        boolean deviceLanguageSupported = false;
        for (String availableLanguage : availableLanguages) {
            if (deviceLanguage.equals(availableLanguage)) {
                deviceLanguageSupported = true;
                break;
            }
        }

        preferences.edit()
                .putString(
                        getResources()
                                .getString(R.string.detail_display_language),
                        deviceLanguageSupported ? deviceLanguage : availableLanguages[0]
                ).commit();

Debugging this code on the first run it enters the above if statement and sets the preference but the preference doesn't show as selected in the preference activity first time around (if I then select it myself, from then onward it appears selected as something).

Am I missing something? I am fairly new to Android. I tried the above based on some other similar SO questions.

PreferenceActivity and PreferenceFragment read preferences from a default preference file. To get access to those preferences you should use PreferenceManager.getDefaultSharedPreferences(context) method.

I am guessing that this is the reason you aren't seeing your changes: you write them to getString(R.string.shared_prefs_key) rather than to the default one.

Try changing your first line to this:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

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