gpt4 book ai didi

android - kotlin.UninitializedPropertyAccessException:lateinit属性首选项尚未初始化

转载 作者:行者123 更新时间:2023-12-02 13:28:30 25 4
gpt4 key购买 nike

我在多个项目中使用了共享首选项的代码,它可以正常工作,但是现在当我在另一个项目中应用相同的代码时,它停止工作。以下是错误

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()方法来实现初始化。
,因此您的代码将如下所示:

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

关于android - kotlin.UninitializedPropertyAccessException:lateinit属性首选项尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62849053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com