问题
I used the code of shared preference in my multiple project and it worked correctly but now when i apply the same code in another project it stopped working. following is error
kotlin.UninitializedPropertyAccessException: lateinit property preferences has not been initialized
Shared preferences code
object AppPrefrence {
private const val NAME = "AComputerEngineer"
private const val MODE = Context.MODE_PRIVATE
private lateinit var preferences: SharedPreferences
private val user_id = Pair("user_id","")
private val ngo_id = Pair("ngo_id","")
private val IS_LOGIN = Pair("is_login", false)
private val catagoryName = Pair("Catagory", "")
private val user_phone = Pair("user_phone", "")
fun init(context: Context) {
preferences = context.getSharedPreferences(NAME, MODE)
}
//an inline function to put variable and save it
private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
val editor = edit()
operation(editor)
editor.apply()
}
var userId: String
get() = preferences.getString(user_id.first, user_id.second) ?: ""
set(value) = preferences.edit {
it.putString(user_id.first, value)
}
var ngoId: String
get() = preferences.getString(ngo_id.first, ngo_id.second) ?: ""
set(value) = preferences.edit {
it.putString(ngo_id.first, value)
}
//SharedPreferences variables getters/setters
var isLogin: Boolean
get() = preferences.getBoolean(IS_LOGIN.first, IS_LOGIN.second)
set(value) = preferences.edit {
it.putBoolean(IS_LOGIN.first, value)
}
var category: String
get() = preferences.getString(catagoryName.first, catagoryName.second) ?: ""
set(value) = preferences.edit {
it.putString(catagoryName.first, value)
}
var userPhone:String
get() = preferences.getString(user_phone.first, user_phone.second)?:""
set(value) = preferences.edit{
it.putString(user_phone.first,value)
}
}
set value in variable
imgBtn_food?.setOnClickListener(View.OnClickListener {
var fd = "food"
catagoryname = fd
AppPrefrence.category = catagoryname.toString()
startActivity(Intent(this, Food_Ngo_Activity::class.java))
})
回答1:
Before accessing the lateinit
variable you should be initialized
it. The initialization can be achieved in your case by calling the method init()
.
So your code will look like below:
AppPrefrence.init(this) // pass your context here
imgBtn_food?.setOnClickListener(View.OnClickListener {
var fd = "food"
catagoryname = fd
AppPrefrence.category = catagoryname.toString()
startActivity(Intent(this, Food_Ngo_Activity::class.java))
})
来源:https://stackoverflow.com/questions/62849053/kotlin-uninitializedpropertyaccessexception-lateinit-property-preferences-has-n