Home > database >  I am getting error while creating global variable for SharedPreferences in kotlin
I am getting error while creating global variable for SharedPreferences in kotlin

Time:06-02

I want to create a global variable for SharedPreferences but it throws an error and offers nothing as a suggestion. what should I do? This error does not happen in other widgets for example when I define button or edittext nothing happens only (as far as I know) in sharedprefences

enter image description here

class SharedPreferences : AppCompatActivity() {
    lateinit var sharedPreferences: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shared_preferences)

        sharedPreferences=this.getSharedPreferences("MAIN_DATA", Context.MODE_PRIVATE)


        var pref=this.getSharedPreferences("MAIN_DATA_2", Context.MODE_PRIVATE)

    }
}

enter image description here

CodePudding user response:

I'm skeptical it doesn't provide an error message. You can hover your cursor over the error and the IDE always explains what the error is.

Your problem is that you named your class SharedPreferences, the exact same name as the Android SharedPreferences class. Since your class is closer in scope than the Android one since this code is inside your class, when you define your property as a SharedPreferences, it's referring to this class, not the Android one. So Activity.getSharedPreferences() is not returning the kind of SharedPreferences that it expects.

Simple solution is to rename your class. By convention an Activity should have the word "Activity" as the last word in its name anyway.

Second solution (FYI only, since you should avoid creating confusing names like this) would be to be explicit about the type you want your SharedPreferences property to be:

lateinit var sharedPreferences: android.content.SharedPreferences

Third solution would be to create a type alias for the Android type so you can use a different name for it. For example:

import android.content.SharedPreferences as AndroidPreferences

//...

lateinit var sharedPreferences: AndroidPreferences

Side note, that is not a global variable. It's a class property. A global variable would be a property defined outside any class.

  • Related