質問

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.

役に立ちましたか?

解決

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?

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top