0

Get SharedPreference values from activity to a fragment

Shared Pref code in activty

val editor =PreferenceManager.getDefaultSharedPreferences(applicationContext).edit()
                        editor.putString("Token", addToken)
                        editor.putString("isNew", 
  response.body()!!.isNew)
                        editor.putString("ccid", 
  response.body()!!.ccId)
                        editor.putString("email", email)
 editor.apply()

SharedPref Code in Fragment

   val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
    token = sharedPreferences.getString("Token", "")
    ccID = sharedPreferences.getString("ccid", "")

How to retrieve the values of shared Preference in a fragment from an Activity.Currently i'm not able to access the token from activity to fragment

RT16
  • 55
  • 2
  • 11

3 Answers3

1

Use getActivity() instaed of context in Fragment

val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

Talha Bilal
  • 167
  • 7
1

If you want to use the context in your Fragment what I did is this :

private val mContext by lazy {
        this@YourFragment.context
}

And then you can use mContext as a Context.

And instead of passing applicationcontextin your Activity send this instead.

val editor =PreferenceManager.getDefaultSharedPreferences(this).edit()
...
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

Did you call commit() method of editor?

See details: What's the difference between commit() and apply() in Shared Preference

Stanley Ko
  • 3,383
  • 3
  • 34
  • 60