android - 当我希望从 Kotlin 中的一个 SharedPreferences 键获得不同的类型值时如何转换类型?
问题描述
代码 B 来自网页,代码 A 会导致错误“java.lang.String cannot be cast to java.lang.Long”。
我尝试分析原因:
首先存储Stringkey="hello"
的SharedPreferences
值,然后我希望从同一个键中获取Long的值,当代码B尝试转换时应用程序崩溃。
我认为代码 B 不好,你能解决它吗?
我猜res as T
代码 B 中的代码很糟糕。
代码 A
val key="hello"
try {
var my1: String by PreferenceTool(this, key, "-1")
my1 = "2"
val my2: Long by PreferenceTool(this, key, -1L)
var ss=my2
}catch (e:Exception){
logError(e.message?:"None")
}
代码 B
class PreferenceTool<T>(private val context: Context, private val name: String, private val default: T) {
private val prefs: SharedPreferences by lazy {
context.defaultSharedPreferences
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
@Suppress("UNCHECKED_CAST")
private fun findPreference(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}
res as T
}
@SuppressLint("CommitPrefEdits")
private fun putPreference(name: String, value: T) = with(prefs.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("This type can't be saved into Preferences")
}.apply()
}
}
解决方案
SharedPreferences 保存类型以及键/值。例如:
<string name="last-version">8.clan.0h</string>
<int name="last-city" value="3" />
<boolean name="record-cached" value="true" />
因此,如果您调用PreferenceTool(this, key, "-1")
,您正在寻找hello
保存为 的 key ,String
它将按预期工作。
但是,如果我们在 SharedPreferences 类中查看 getLong 的实现:
/**
* Retrieve a long value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a long.
*
* @throws ClassCastException
*/
long getLong(String key, long defValue);
键hello
的类型保存为String
,因此当您PreferenceTool
调用时,getLong
您将获得ClassCastException
文档中的一个。
您可以在此处查看文档:
推荐阅读
- python - 为 Pandas 系列浮点数分配日期
- php - 通过 AJAX/PHP 从 MySQL 中检索数据
- java - Android:在 Messenger 应用程序中用“Intent.putExtra()”替换字段中的文本失败
- java - 动态读取 CSV 文件
- android - 如何使用按钮使应用程序全屏显示
- session - ARKit 共享世界地图会话文件
- bash - 如何使用 bash 循环替换 fasta 文件中的行中的字母?
- ios - 使用 iOS 12.1 SDK 构建原生脚本应用程序时出现问题
- visual-studio-code - 缺少 Visual Studio Code 终端底部/顶部按钮
- npm - NPM 和“并发”失败