Search code examples
javaandroidlistpreferenceandroid-multiselectlistpreference

MultiSelectListPreference get Checked values?


Hi guy im would like to do a easy newsreader app. in shared preferences the user could choose which news sections he can see. I com until the Point to add MultiSelectListPreference and retrieve th values. But unfortunatly it retrieves all values and not only the checked.

Here is my code:

<MultiSelectListPreference
            android:id="@+id/multiple_choice"
            android:dialogTitle="@string/section_news_label"
            android:entries="@array/news_sections"
            android:entryValues="@array/section_values"
            android:key="section_news_key"
            android:summary="@string/section_hint"
            android:defaultValue="@array/default_array"
            />

public class SettingsActivity extends AppCompatActivity {

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

    public static class NewsPreferenceFragment extends PreferenceFragment
            implements Preference.OnPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings_main);

            Preference newsToShow = findPreference(getString(R.string.settings_news_show_key));
            bindPreferenceSummaryToValue(newsToShow);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();
            preference.setSummary(stringValue);
            return true;
        }

        private void bindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(this);
            SharedPreferences preferences =
                    PreferenceManager.getDefaultSharedPreferences(preference.getContext());
            String preferenceString = preferences.getString(preference.getKey(), "");
            onPreferenceChange(preference, preferenceString);
        }
    }
}

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);


        Set<String> entries = sharedPrefs.getStringSet("section_news_key", null);
         if(entries == null){
             Log.v("!!!!!!!!!", "No entries");
         }else {
             Log.v("!!!!!!!!!", entries.toString());
         }

Any idea what im doing wrong?


Solution

  • Thanks, I found a solution that works for me. You will need to use a HashSet.

    //Get entries from news sections and store in Set
    Set<String> entries = sharedPrefs.getStringSet("section_news_key", new HashSet<String>());