[英]Kotlin Android Shared Preferences - lateinit property prefs has not been initialized
I tried to follow this tutorial , but an error occured when I try to assign a value to my Sh.Preference ( prefs.token = "sometoken"
):我尝试按照本教程进行操作,但是当我尝试为我的 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 :首选项.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 :应用程序.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? prefs.token
的默认值为""
,那么为什么日志说尚未初始化?
Ok, problem found... The code was alright, I just missed to add this line好的,问题找到了...代码没问题,我只是错过了添加这一行
android:name=".App"
in the tag <application
in my Android Manifest.在我的 Android 清单中的<application
标签中。
In my case, i just initialize SharedPreference in onCreate()
, and all works就我而言,我只是在onCreate()
初始化 SharedPreference ,并且一切正常
For example: MainActivity.kt例如: MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppPreferences.init(this) // added this
}
SharedPreferences object: SharedPreferences 对象:
object AppPreferences {
private const val NAME = "SpinKotlin"
private const val MODE = Context.MODE_PRIVATE
private lateinit var preferences: SharedPreferences
// list of app specific preferences
private val IS_FIRST_RUN_PREF = Pair("is_first_run", false)
fun init(context: Context) {
preferences = context.getSharedPreferences(NAME, MODE)
}
/**
* SharedPreferences extension function, so we won't need to call edit() and apply()
* ourselves on every SharedPreferences operation.
*/
private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
val editor = edit()
operation(editor)
editor.apply()
}
// getter and setter with Shared Preference
var temperature: Float
// custom getter to get a preference of a desired type, with a predefined default value
get() = preferences.getFloat("temp",1f )
// custom setter to save a preference back to preferences file
set(value) = preferences.edit {
it.putFloat("temp", value)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.