首页 > 解决方案 > 意图 putExtra 值的 Android Kotlin 测试

问题描述

android studio 4.1.1和科特林。我是通过教程学习的初学者。

我有一项活动,我正在使用 Intent 进行另一项活动。我正在使用intent.putExtra

val intent = Intent(this, WeightExercise::class.java)
intent.putExtra("POSITION", positionToString)
startActivity(intent)

在 WeightExercise 活动中,我得到传递的值:

// with line numbers:

80: var myPosition = intent.getStringExtra("POSITION").toString()
81: var position = myPosition.toInt()

这行得通。我在POSITION.

问题:我有另一个使用 Intent 进入 WeightExercise 活动的活动。它不是通过意图传递值。发生这种情况时,WeightExercise 活动中的第 81 行(上图)会导致错误:

Caused by: java.lang.NumberFormatException: For input string: "null"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.johndcowan.liftit.WeightExercise.onCreate(WeightExercise.kt:81)

我已经尝试了几个if()s 来测试 null 或空值,但没有什么能让我越过这个错误。

if ( intent.getStringExtra("POSITION").toString().isNullOrEmpty() ) {...}
if ( myPosition.isNullOrEmpty() ) {...}
if ( myPosition == null ) {...}

有没有更好的方法来测试POSITION意图中的命名字符串?

感谢您的任何提示。

标签: android-studiokotlinandroid-intent

解决方案


您可以利用 Kotlin Null Safety

如果需要,当 extra 为 null 时设置默认值。

var myPosition = intent?.extras?.getStringExtra("POSITION") ?: DEFAULT_VALUE

查找有关?:猫王运算符的更多信息


推荐阅读