我将设备令牌保存在共享的首选项中,并且仅在第二次运行时设法获得它。 这是代码:
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()
我在一个片段中访问它,并将令牌存储在Firebase服务中或将应用程序初始化为int
prefs = PreferencesHelper(context!!)
preds.token... //returns empty string.
什么可能导致首选项仅在首次运行后起作用?
答案 0 :(得分:1)
您没有正确进行吸气剂。实际上,您根本就没有这样做。
即使在Kotlin中,也使用=
来分配变量,而不会在初始化时分配它。
更改:
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()
收件人:
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()