android-studio - 意图 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
意图中的命名字符串?
感谢您的任何提示。
解决方案
您可以利用 Kotlin Null Safety
如果需要,当 extra 为 null 时设置默认值。
var myPosition = intent?.extras?.getStringExtra("POSITION") ?: DEFAULT_VALUE
查找有关?:
猫王运算符的更多信息
推荐阅读
- javascript - 获取所有标题并递归创建树
- javascript - 使用 JavaScript,是否可以从传出的获取请求中捕获正文有效负载?
- node.js - Express 服务于 2 个不同的 Angular PWA
- java - 模型映射器中的延迟初始化异常
- node.js - vue客户端套接字未连接到服务器
- php - PHP:只有唯一对的嵌套循环
- python - 带有 Authlib 0.11 的 JWT 令牌生成器
- git - Missing the + parameter in git push after git rebase
- python - 在 infytq 应用程序中解决问题时出现问题
- javascript - Animate being triggered multiple times