Reputation: 135
I am soo frustrated. In my very simple MainActivity I created a very simple Preference and everything works fine. I can display the value in other Activities, there are no errors or something.
preference = getSharedPreferences("testPreference", Context.MODE_PRIVATE)
val editor = preference.edit()
editor.putString("nameOfUser", "TEST")
editor.apply()
Now I created a SettingsFragment and I want to display in this Fragment the value of the SharedPreferences - and it doesn't work. I tried like the example above, but it shows me the value null
. I don't understand it why is it soooo difficult, when I'm using a Fragment?
Fragment:
var preference: SharedPreferences? = context?.getSharedPreferences("testPreference", 0)
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences_profilesettings, rootKey)
println(preference?.getString("nameOfUser", "error"))
}
Upvotes: 0
Views: 269
Reputation: 69681
You are using a different Preferences
name inside your SettingsFragment
check
You need to Use testPreference
Instead of nameOfUser
Use this
preference = getSharedPreferences("testPreference", Context.MODE_PRIVATE)
Instead of
preference = getSharedPreferences("nameOfUser", Context.MODE_PRIVATE)
UPDATE
lateinit preference: SharedPreferences
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
preference = context?.getSharedPreferences("testPreference", 0)
setPreferencesFromResource(R.xml.preferences_profilesettings, rootKey)
println(preference?.getString("nameOfUser", "error"))
}
Upvotes: 2
Reputation: 18677
Problem is here:
var preference: SharedPreferences? = context?.getSharedPreferences("testPreference", 0)
When the Fragment
is created, there's no Context
associated with it yet. So, you can't use Context
in the preference declaration.
Try something like:
var lateinit preference: SharedPreferences
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
preference = context?.getSharedPreferences("testPreference", 0)
setPreferencesFromResource(R.xml.preferences_profilesettings, rootKey)
println(preference?.getString("nameOfUser", "error"))
}
The same error does not happen with an Activity
because an Activity
is also a Context
. Fragment
s on the other hand aren't Context
. It receives a Context
sometime later after its creation via onAttach(Context context)
Upvotes: 1