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

Adapter中用变量设背景色触发StringIndexOutOfBoundsException原因排查

问题分析与解决:RecyclerView绑定中Color.parseColor抛出StringIndexOutOfBoundsException

问题重现

绑定方法代码

override fun onBindViewHolder(holder: bomViewHolder, position: Int) {
  val color=ListTheColorTone[position].color
  holder.cardBlack.setCardBackgroundColor(Color.parseColor(color!!))
}

错误栈

java.lang.StringIndexOutOfBoundsException: length=0; index=0
  at java.lang.String.charAt(Native Method)
  at android.graphics.Color.parseColor(Color.java:1384)
  at com.example.wallpaperapp.Adapter.colortoneAdapter.onBindViewHolder(colortoneAdapter.kt:33)
  at com.example.wallpaperapp.Adapter.colortoneAdapter.onBindViewHolder(colortoneAdapter.kt:15)
  at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
  at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
  at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline (RecyclerView.java:6012)

手动传入parseColor("#ffffff")可正常运行,仅使用数据源中的字符串时崩溃。

问题原因

错误栈明确显示,Color.parseColor在调用charAt(0)时触发数组越界,说明传入的color是空字符串(长度为0)。你用!!强制非空,但空字符串不等于null,所以!!不会触发空指针异常,却让无效的空字符串进入parseColor方法导致崩溃。

解决方案

1. 校验数据源

检查ListTheColorTone集合,确保每个元素的color字段都是非空且符合颜色格式的字符串(如#ffffff、#fff、red等合法值),排查是否存在空字符串的元素。

2. 增加代码防御性判断

修改绑定方法,加入空值、空字符串校验,同时捕获非法格式异常,避免崩溃:

override fun onBindViewHolder(holder: bomViewHolder, position: Int) {
    val colorStr = ListTheColorTone[position].color?.trim()
    val defaultColor = Color.WHITE // 可根据需求替换为合适的默认颜色
    val targetColor = when {
        colorStr.isNullOrEmpty() -> defaultColor
        !colorStr.startsWith("#") -> defaultColor // 仅允许#开头的十六进制颜色,可根据需求调整规则
        else -> try {
            Color.parseColor(colorStr)
        } catch (e: IllegalArgumentException) {
            defaultColor
        }
    }
    holder.cardBlack.setCardBackgroundColor(targetColor)
}

3. 从源头过滤无效数据

如果ListTheColorTone是从网络接口、数据库或本地文件读取的,在数据解析/入库阶段就过滤掉color为空或格式非法的元素,避免异常数据流入UI层。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:20:34