这段时间也没啥写啥文章,写一下我现在在项目中使用sp的方法。这个也是我看别人写的,感觉好的话也可以在你的项目中使用,个人感觉还是挺方便的。
一.创建SpHelper.kt
package com.tk.checkreinforce.util.core
import android.content.Context
private const val SP = "sp"
@JvmOverloads
fun <T> getSpValue(
filename: String = SP,
context: Context,
key: String,
defaultVal: T
): T {
val sp = context.getSharedPreferences(filename, Context.MODE_PRIVATE)
return when (defaultVal) {
is Boolean -> sp.getBoolean(key, defaultVal) as T
is String -> sp.getString(key, defaultVal) as T
is Int -> sp.getInt(key, defaultVal) as T
is Long -> sp.getLong(key, defaultVal) as T
is Float -> sp.getFloat(key, defaultVal) as T
is Set<*> -> sp.getStringSet(key, defaultVal as Set<String>) as T
else -> throw IllegalArgumentException("Unrecognized default value $defaultVal")
}
}
@JvmOverloads
fun <T> putSpValue(
filename: String = SP,
context: Context,
key: String,
value: T
) {
val editor = context.getSharedPreferences(filename, Context.MODE_PRIVATE).edit()
when (value) {
is Boolean -> editor.putBoolean(key, value)
is String -> editor.putString(key, value)
is Int -> editor.putInt(key, value)
is Long -> editor.putLong(key, value)
is Float -> editor.putFloat(key, value)
is Set<*> -> editor.putStringSet(key, value as Set<String>)
else -> throw UnsupportedOperationException("Unrecognized value $value")
}
editor.apply()
}
@JvmOverloads
fun removeSpValue(filename: String = SP, context: Context, key: String) {
context.getSharedPreferences(filename, Context.MODE_PRIVATE)
.edit()
.remove(key)
.apply()
}
@JvmOverloads
fun clearSpValue(filename: String = SP, context: Context) {
context.getSharedPreferences(filename, Context.MODE_PRIVATE)
.edit()
.clear()
.apply()
}
二.使用
fun setUserId(userId: String) = putSpValue(KEY_USER_ID, App.instance, KEY_USER_ID, userId)
fun getUserId(): String = getSpValue(KEY_USER_ID, App.instance, KEY_USER_ID, "")
直接可以在任何一个类中使用putSpValue()与getSpValue()方法,你也可以创建一个二级目录例如专门保存用户信息的UserInfoStore类然后在封装方法。