3

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?

giacom0c
  • 259
  • 1
  • 6
  • 18

2 Answers2

4

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.

giacom0c
  • 259
  • 1
  • 6
  • 18
0

In my case, i just initialize SharedPreference in onCreate(), and all works

For example: MainActivity.kt

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

SharedPreferences object:

    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)
            }
    }
Arsen Tagaev
  • 411
  • 7
  • 13