Reputation: 23
I am currently struggling with Kotlin for my Bachelor thesis and I have no idea what I am doing.
So here is my problem:
I created a (functional) settings activity with multiple EditTextPreferences and a ListPreference. Right now I want to retrieve the selected item from the ListPreference in another activity. This is my ListPreference:
<ListPreference
android:dialogTitle="Art des Implantates"
android:entries="@array/settings_list_preference_titles"
android:entryValues="@array/settings_list_preference_values"
android:key="list"
android:title="Implantat"
app:useSimpleSummaryProvider="true"/>
So how do I retrieve the selected Item? Let's say I just want to display it somewhere else. I have no clue whatsoever, since every single Tutorial I came across is for java and I don't speak java.
Please help me. I'm desperate.
Upvotes: 2
Views: 1764
Reputation: 135
If you are using java:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
You can access values by using XML app:key="this_value" like this:
prefs.getString("this_value","some_val");
Upvotes: 0
Reputation: 1006614
Step #1: Get a SharedPreferences
object for the default preferences:
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
(where context
is a Context
, such as an Activity
or the Application
singleton)
Step #2: Call getString("list", someDefaultValue)
on the SharedPreferences
, where "list"
is your key (from your <ListPreference>
) and someDefaultValue
is a String
that you want returned if the user has not yet set this preference
since every single Tutorial I came across is for java
This sample app (from this book) is in Kotlin and shows the use of SharedPreferences
. The documentation also shows the use of SharedPreferences
with Kotlin (and Java).
Upvotes: 4