Zach Bublil
Zach Bublil

Reputation: 867

Get value from shared preferences in first time is not working

I save the device token in shared preferences and I only manage to get it on the second run. This is the code:

class PreferencesHelper(context: Context) {

companion object {
    private val usernameKey = "username_key"
    private val passKey = "pass_key"
    private val tokenKey = "token_key"
}

private val preferences = PreferenceManager.getDefaultSharedPreferences(context)

var username = preferences.getString(usernameKey, "")
    set(value) = preferences.edit().putString(usernameKey, value).apply()

var password = preferences.getString(passKey, "")
    set(value) = preferences.edit().putString(passKey, value).apply()

var token = preferences.getString(tokenKey, "")
    set(value) = preferences.edit().putString(tokenKey, value).apply()

I access it in a fragment and I store the token in the firebase service or int the app init

  prefs = PreferencesHelper(context!!)
  preds.token... //returns empty string.

What can may cause preferences works only after the first run?

Upvotes: 0

Views: 570

Answers (1)

TheWanderer
TheWanderer

Reputation: 17834

You're not doing getters correctly. In fact, you're not doing them at all.

Using = for a variable, even in Kotlin, assigns it on initialization and never again.

Change:

var username = preferences.getString(usernameKey, "")
    set(value) = preferences.edit().putString(usernameKey, value).apply()

var password = preferences.getString(passKey, "")
    set(value) = preferences.edit().putString(passKey, value).apply()

var token = preferences.getString(tokenKey, "")
    set(value) = preferences.edit().putString(tokenKey, value).apply()

To:

var username: String
    get() = preferences.getString(usernameKey, "")
    set(value) = preferences.edit().putString(usernameKey, value).apply()

var password: String
    get() = preferences.getString(passKey, "")
    set(value) = preferences.edit().putString(passKey, value).apply()

var token: String
    get() = preferences.getString(tokenKey, "")
    set(value) = preferences.edit().putString(tokenKey, value).apply()

Upvotes: 1

Related Questions