Kotlin Android共享首选项-lateinit属性首选项尚未初始化

时间:2018-07-11 22:30:38

标签: android kotlin sharedpreferences

我尝试遵循this tutorial,但是当我尝试为Sh.Preference(prefs.token = "sometoken")赋值时发生错误:

kotlin.UninitializedPropertyAccessException: lateinit property prefs has not been initialized

我不知道错误在哪里,我还检查了this thread。 这是我的代码段

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的默认值为"",那么为什么日志说尚未初始化?

2 个答案:

答案 0 :(得分:1)

好,发现问题了……代码还可以,我只是错过了添加这一行

android:name=".App"
标签中的

 <application在我的Android清单中。

答案 1 :(得分:0)

就我而言,我只是在onCreate()中初始化SharedPreference,并且一切正常

例如: MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AppPreferences.init(this) // added this
}

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)
            }
    }