kotlin.UninitializedPropertyAccessException:lateinit属性首选项尚未初始化 [英] kotlin.UninitializedPropertyAccessException: lateinit property preferences has not been initialized
本文介绍了kotlin.UninitializedPropertyAccessException:lateinit属性首选项尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在多个项目中使用了共享首选项的代码,它可以正常工作,但是现在当我在另一个项目中应用相同的代码时,它就停止了工作.以下是错误
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属性首选项尚未初始化
kotlin.UninitializedPropertyAccessException: lateinit property preferences has not been initialized
共享的首选项代码
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)
}
}
在变量中设置值
imgBtn_food?.setOnClickListener(View.OnClickListener {
var fd = "food"
catagoryname = fd
AppPrefrence.category = catagoryname.toString()
startActivity(Intent(this, Food_Ngo_Activity::class.java))
})
推荐答案
在访问lateinit
变量之前,您应先initialized
它.您可以通过调用方法init()
来实现初始化.
Before accessing the lateinit
variable you should be initialized
it. The initialization can be achieved in your case by calling the method init()
.
因此您的代码如下所示:
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))
})
这篇关于kotlin.UninitializedPropertyAccessException:lateinit属性首选项尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文