Hel*_*oCW 0 android kotlin androidx
通常,我使用代码 A 或代码 B 来读取或写入 SharedPreferences。
目前,我更新了我的项目以"androidx.preference:preference-ktx:1.1.1"与 Kotlin 一起使用。
当我与 Kotlin 一起使用时,是否有更好的方法来读取和写入 SharedPreferences "androidx.preference:preference-ktx:1.1.1"?
代码A
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
Run Code Online (Sandbox Code Playgroud)
代码B
SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
Run Code Online (Sandbox Code Playgroud)
如果您不使用依赖注入工具,例如hilt、等,最好创建一个管理首选项值的单例类,以免每次您想要读取或写入值时都获取koin对象。帮助您以线程安全的方式创建带有参数的单例类。SharedPreferencesSingletonHolder
否则,如果您在项目中使用依赖项注入工具,则可以跳过以下解决方案的单例部分并让 DI 工具来完成。
import android.content.Context
class PrefManager private constructor(context: Context) {
// ------- Preference Variables
var authenticationId: String?
get() = pref.getString("KEY_AUTHENTICATION_ID", null)
set(value) = pref.edit { putString("KEY_AUTHENTICATION_ID", value) }
var authenticationStatus: Boolean
get() = pref.getBoolean("KEY_AUTHENTICATION_STATUS", false)
set(value) = pref.edit { putBoolean("KEY_AUTHENTICATION_STATUS", value) }
// ---------------------------------------------------------------------------------------------
private val pref = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
fun clear() = pref.edit { clear() }
companion object : SingletonHolder<PrefManager, Context>(::PrefManager) {
private const val FILE_NAME = "AUTHENTICATION_FILE_NAME"
}
}
Run Code Online (Sandbox Code Playgroud)
open class SingletonHolder<out T, in A>(private val constructor: (A) -> T) {
@Volatile
private var instance: T? = null
fun getInstance(arg: A): T {
return when {
instance != null -> instance!!
else -> synchronized(this) {
if (instance == null) instance = constructor(arg)
instance!!
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以读取如下值:
val authenticationId = PrefManager.getInstance(context).authenticationId
Run Code Online (Sandbox Code Playgroud)
为了写:
PrefManager.getInstance(context).authenticationId = "SOME VALUE"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2843 次 |
| 最近记录: |