Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all selected entries from MultiSelectListPreference(SharedPreferences)

I want to use MultiSelectListPreference to create an array of items and to search for them in an xml.

I created the MultiSelectListPreference in XML (res/xml/preferences.xml)

<MultiSelectListPreference
            android:dialogTitle="@string/coursesTitle"
            android:key="searchedCourses"
            android:summary=""        
            android:title="@string/coursesTitle"
            android:entries="@array/courses"
            android:entryValues="@array/courses"
            android:defaultValue="@array/empty_array"
            android:dependency="own_courses"
           />

I created a Preference Fragment and a Preference Activity. I already can chose the items i want to search for.

Now I want to read out the selected items.

I tried with

SharedPreferences sharedPref =   PreferenceManager.getDefaultSharedPreferences(this);
 String rawval = sharedPref.getString("searchedCourses", "NA");
 String[] selected = this(context, null).parseStoredValue(rawval);

 Toast.makeText(context, selected[0], Toast.LENGTH_LONG).show();

and similar 'solutions' I found online, but it does not work.

like image 693
user2958172 Avatar asked Nov 05 '13 21:11

user2958172


2 Answers

Though not deeply familiar with them, I would expect this to work:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Set<String> selections = sharedPrefs.getStringSet("searchedCourses", null);

Toast.makeText(context, selections.get(0), Toast.LENGTH_LONG).show();

What behavior are you seeing?

like image 127
blahdiblah Avatar answered Nov 20 '22 06:11

blahdiblah


Thank you :) the getStringSet() method was the solution. I changed the code a little though:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Set<String> selections = sharedPrefs.getStringSet("searchedCourses", null);
String[] selected = selections.toArray(new String[] {});
Toast.makeText(context, selected[all], Toast.LENGTH_LONG).show();

I am really grateful.

PS: your solution lead to an erro: The method get() is undefined for the type Set. Don't know why.

like image 33
user2958172 Avatar answered Nov 20 '22 07:11

user2958172