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

Kotlin开发Android时Activity接收Intent传值为null排查

问题原因

出现显示null的核心原因是Intent传参时的类型不匹配:

  • 传值阶段:你在MainActivity中调用putExtra("username",findViewById<TextView>(R.id.username).text)时,传入的参数是CharSequence类型(从loadButton的点击事件可以看出R.id.username实际是EditText控件,其text属性返回的是Editable类型,属于CharSequence子类),并非String类型。
  • 取值阶段:DisplayActivity中调用的getStringExtra("username")只会读取Bundle中以String类型存储的对应key值,由于之前存入的不是String类型,该方法会直接返回null,后续调用toString()就会把null转为字符串"null"显示在页面上。
修复方法

方案1(推荐):传值时明确转为String类型

修改MainActivity中跳转传值的代码,在获取文本后主动调用toString()转为String再存入Intent:

button.setOnClickListener {
    startActivity(Intent(this,DisplayActivity::class.java)
        // 末尾追加.toString()转换类型
        .putExtra("username", findViewById<TextView>(R.id.username).text.toString()))
}

方案2:取值时匹配存入的类型

如果不修改传值逻辑,也可以在DisplayActivity取值时改用getCharSequenceExtra匹配存入的CharSequence类型,再转成字符串:

// 匹配存入的CharSequence类型取值,再做非空兜底
val username = intent.getCharSequenceExtra("username")?.toString() ?: ""
findViewById<TextView>(R.id.username1).text = username
额外优化建议
  • 避免在点击事件回调里反复调用findViewById查找控件,可以在onCreate阶段一次性绑定控件实例复用,减少性能损耗。
  • 调用getStringExtra这类可能返回null的方法时,建议加上空值兜底逻辑,避免触发空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:18:20