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

Android中SharedPreferences存值后无法获取对应值求助

问题分析与解决方案

从日志和代码来看,存储操作已记录成功,但获取时始终返回默认值,核心问题可能出在以下几点:

1. 获取函数的逻辑严谨性不足

当前getWidgetPref使用并列if判断类型,虽然不会出现同一对象匹配多类型的情况,但改用when表达式更清晰,也能避免潜在的逻辑漏洞:

internal fun getWidgetPref(context: Context, appWidgetId: Int, key: String, typeValue: Any): Any? {
    val prefs = get_pref(context)
    val path = get_path(appWidgetId, key)
    
    // 用when替代并列if,逻辑更清晰
    return when (typeValue) {
        is Boolean -> prefs.getBoolean(path, false)
        is String -> prefs.getString(path, "do")
        else -> null
    }.also {
        Log.d("custom", "Value found for $path: $it")
    }
}

2. 未确认存储操作是否真正成功

commit()方法会返回布尔值表示是否提交成功,添加日志确认存储是否写入磁盘:

internal fun saveWidgetPref(context: Context, appWidgetId: Int, key: String, value: Any) {
    val prefs = get_pref(context).edit()
    val path = get_path(appWidgetId, key)
    
    when (value) {
        is Boolean -> prefs.putBoolean(path, value)
        is String -> prefs.putString(path, value)
    }
    
    // 打印提交结果,确认是否存储成功
    val isSaved = prefs.commit()
    Log.d("custom", "Value stored for $path: $value, save success: $isSaved")
}

3. 调用获取函数时传入的类型参数错误

确保调用getWidgetPref时,传入的typeValue类型与存储的类型完全匹配:

  • 获取字符串时,传入String类型实例(如空字符串""):
    val widgetLabel = getWidgetPref(context, 154, "widget_label", "") as String
    
  • 获取布尔值时,传入Boolean类型实例(如默认值false):
    val portailChecked = getWidgetPref(context, 154, "Portail", false) as Boolean
    

4. 验证Key是否存在

在获取函数中添加日志,检查目标Key是否真的存在于SharedPreferences中:

internal fun getWidgetPref(context: Context, appWidgetId: Int, key: String, typeValue: Any): Any? {
    val prefs = get_pref(context)
    val path = get_path(appWidgetId, key)
    
    // 检查Key是否存在
    Log.d("custom", "Key $path exists: ${prefs.contains(path)}")
    
    return when (typeValue) {
        is Boolean -> prefs.getBoolean(path, false)
        is String -> prefs.getString(path, "do")
        else -> null
    }.also {
        Log.d("custom", "Value found for $path: $it")
    }
}

如果contains(path)返回false,说明存储操作未真正写入,此时需要检查设备磁盘空间、应用权限,或是否有其他代码删除了该Key。

内容的提问来源于stack exchange,提问作者corazon008

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:22:17