首页 > 解决方案 > 当我希望从 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()
    }
}

标签: androidkotlin

解决方案


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文档中的一个。

您可以在此处查看文档:


推荐阅读