You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:从SharedPreference读取Integer时抛出Boolean无法转为Integer异常

java.lang.Boolean cannot be cast to java.lang.Integer in SharedPreference

我一眼就揪出问题根源了——你这个"key"对应的实际存储类型是Boolean,但你现在用getInt()方法去读取,类型不匹配直接触发了强制转换异常。

为什么会这样?

SharedPreference的键值对是严格绑定类型的:你存的时候用了什么类型的putXxx()方法,取的时候就得用对应的getXxx()方法。比如你之前大概率不小心用了edit().putBoolean("key", true/false)把这个键存成了布尔值,现在调用getInt()时,SharedPreference内部会尝试把存储的Boolean对象强转成Integer,这自然就炸了。

解决步骤

  1. 修正存储逻辑
    首先确保后续存这个键时用正确的类型方法:

    mSharedPref.edit().putInt("key", yourTargetIntValue).apply();
    
  2. 清除旧的错误数据(测试环境适用)
    如果是开发测试阶段,直接卸载App重新安装,或者在系统设置里清除App的存储数据,旧的布尔值会被彻底清除,之后就能正常读写int类型了。

  3. 兼容旧数据(线上环境适用)
    如果不能清除用户的旧数据,就得做兼容处理,先判断存储值的类型再读取:

    public Integer readIntData(String key, int defaultValue){ 
        mSharedPref = context.getApplicationContext().getSharedPreferences(context.getString(R.string.shared_pref_app), Context.MODE_PRIVATE); 
        Map<String, ?> allEntries = mSharedPref.getAll();
        if (allEntries.containsKey(key)) {
            Object storedValue = allEntries.get(key);
            if (storedValue instanceof Boolean) {
                // 根据业务需求把布尔值转成int,比如true转1,false转0
                return ((Boolean) storedValue) ? 1 : 0;
            } else if (storedValue instanceof Integer) {
                return (Integer) storedValue;
            } else {
                return defaultValue;
            }
        }
        return defaultValue;
    }
    

后续预防建议

  • 永远保证同一个key的存、取方法类型一致,比如putInt()对应getInt(),putBoolean()对应getBoolean(),绝对不要混用。
  • 团队协作时,建议把SharedPreference的所有键和对应的类型统一维护在一个常量类里,避免出现类型混乱的情况。

内容的提问来源于stack exchange,提问作者CLIFFORD P Y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:07:55