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

Android DataBinding报错:无法在Statistic类中找到get()方法

问题分析

报错cannot find method get() in class Statistic的核心原因是嵌套数据类同名导致DataBinding解析歧义:

  • 在FixtureById.Response.Statistic内部定义了另一个同名的Statistic数据类,当DataBinding解析statistic.statistics.get(0).statistics.get(9)时,会错误地将第二个statistics后的get(9)理解为调用FixtureById.Response.Statistic类的方法,而非List的get(index)方法。
  • 另外所有字段都是可空类型,直接链式调用存在空指针风险,这也是潜在问题。
解决方案

1. 重命名内部同名数据类

修改嵌套的Statistic类名称,避免与外层类冲突,比如改为StatDetail:

data class FixtureById(
    @SerializedName("get")
    val `get`: String?,
    @SerializedName("response")
    val response: List<Response?>?,
) {
    data class Response(
        @SerializedName("statistics")
        val statistics: List<Statistic?>?,
    ) {
        data class Statistic(
            @SerializedName("statistics")
            val statistics: List<StatDetail?>?, // 修改为StatDetail
            @SerializedName("team")
            val team: Team?
        ) {
            // 重命名为StatDetail
            data class StatDetail(
                @SerializedName("type")
                val type: String?,
                @SerializedName("value")
                val value: Int?
            )

            data class Team(
                @SerializedName("id")
                val id: Int?,
                @SerializedName("logo")
                val logo: String?,
                @SerializedName("name")
                val name: String?
            )
        }
    }
}

2. 修正DataBinding表达式,处理空安全

修改布局中的绑定表达式,使用安全调用(?.)和Elvis运算符(?:)避免空指针,同时适配重命名后的类:

<TextView
    android:text="@{statistic.statistics?.get(0)?.statistics?.get(9)?.value?.toString() ?: \"0\"}"
    android:textStyle="bold"
    android:textSize="20sp"
    android:textColor="@color/holo_green_light"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:layout_gravity="center"/>

3. 完善数据赋值逻辑

当前赋值逻辑合法,可补充空判断增强鲁棒性:

responseState.data?.response?.get(0)?.let { statistic ->
    binding.statistic = statistic
} ?: run {
    // 处理数据为空的场景
}
补充说明
  • 嵌套类同名会干扰Kotlin类型推断和DataBinding表达式解析,属于常见命名陷阱,建议嵌套类使用语义明确的名称,避免与外层类或字段重名。
  • DataBinding中调用List的get(index)方法是合法操作,但必须确保调用对象确实为List类型,同名类会打破这一解析逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:42:35