I tried to follow this tutorial, but an error occured when I try to assign a value to my Sh.Preference (prefs.token = "sometoken"
):
kotlin.UninitializedPropertyAccessException: lateinit property prefs has not been initialized
I don't understand where's the bug, I also checked this thread. Here are my code snippets
Prefs.kt :
class Prefs(context: Context) {
private val PREFS_FILENAME = "com.example.myapp.prefs"
private val PREFS_TOKEN = "token"
private val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME, 0)
var token: String?
get() = prefs.getString(PREFS_TOKEN, "")
set(value) = prefs.edit().putString(PREFS_TOKEN, value).apply()
}
App.kt :
val prefs: Prefs by lazy {
App.prefs
}
class App : Application() {
companion object {
lateinit var prefs: Prefs
}
override fun onCreate() {
prefs = Prefs(applicationContext)
super.onCreate()
}
}
prefs.token
has a default value of ""
, so why the logs said that has not been initialized?