Android: Get all selected records from MultiSelectListPreference (SharedPreferences)

I am new to Android, and this question may be easy to solve, but I have been searching and trying for more than 4 hours to get data.

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

I created a 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 function. I can already select the items I want to find.

Now I want to read the selected items.

I tried using

 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" that I found on the Internet, but this does not work.

I hope you understand me, and you can help me. Thanks and greetings from Germany.

+6
source share
2 answers

Although he is not 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 kind of behavior do you see?

+8
source

Thanks :) the getStringSet () method was a solution. I changed the code a bit:

 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 very grateful.

PS: your solution will result in erro: the get () method is undefined for the type Set. I do not know why.

+3
source

Source: https://habr.com/ru/post/957456/


All Articles