Android Studio中Kotlin代码出现NumberFormatException问题求助
NumberFormatException 空字符串转Int异常排查与解决
问题现象
此前运行正常的Kotlin代码近期抛出NumberFormatException,错误日志明确显示是空字符串转换为Int时触发的异常:
E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NumberFormatException: For input string: "" at java.lang.Integer.parseInt(Integer.java:627) at java.lang.Integer.parseInt(Integer.java:650) at jdd.com.ng.jddwebmaster.jddstore.code.ui.activities.CartListActivity.successfullyGetCartItemList(CartListActivity.kt:100)
关联代码
CartListActivity关键代码
private lateinit var mCartListItem: ArrayList<CartItem> for (item in mCartListItem){ val availableQuantity = item.stock_quantity.toInt() if(availableQuantity > 0){ // convert the price to double val price = item.product_price.toDouble() // convert the quantity order to Int val quantity = item.cart_quantity.toInt() // calculate the sub total subTotal += (price * quantity) } }
CartItem数据类
@Parcelize data class CartItem( val user_id: String = "", val product_owner_id: String = "", val product_id: String = "", val product_title: String = "", val product_price: String = "", val product_image: String = "", var cart_quantity: String = "", var stock_quantity: String = "", var id: String = "" ): Parcelable
问题根源
- 数据类型设计缺陷:
CartItem中stock_quantity、cart_quantity、product_price均为String类型,默认值是空字符串"",但这些本质是数值型数据 - 转换逻辑无安全校验:直接调用
toInt()/toDouble()方法,当字符串为空(或非数字格式)时,会直接抛出NumberFormatException - 数据内容变化触发异常:此前数据中这些字段均为有效数字字符串,近期出现空值情况,导致原本正常的代码崩溃
解决方案
方案1:安全转换(快速修复)
使用Kotlin提供的toIntOrNull()/toDoubleOrNull()方法,配合空合并运算符?:处理空值或非法格式的情况,避免抛出异常:
for (item in mCartListItem){ // 空字符串或非数字时默认转为0 val availableQuantity = item.stock_quantity.toIntOrNull() ?: 0 if(availableQuantity > 0){ // 价格转换同理,空值默认0.0 val price = item.product_price.toDoubleOrNull() ?: 0.0 val quantity = item.cart_quantity.toIntOrNull() ?: 0 subTotal += (price * quantity) } }
方案2:优化数据类设计(从根源避免)
将数值类型的字段直接定义为Int/Double(或可空类型),彻底避免字符串转换的风险:
@Parcelize data class CartItem( val user_id: String = "", val product_owner_id: String = "", val product_id: String = "", val product_title: String = "", val product_price: Double = 0.0, val product_image: String = "", var cart_quantity: Int = 0, var stock_quantity: Int = 0, var id: String = "" ): Parcelable
注:如果数据来自Firebase等后端,需确保序列化/反序列化时能正确将数字字符串转换为对应数值类型,可配合自定义转换器实现。
方案3:数据来源前置校验
在获取CartItem数据的环节(比如Firestore读取后),提前校验并修复空值:
// 示例:Firestore读取后处理数据 fun processCartItems(rawItems: List<CartItem>): List<CartItem> { return rawItems.map { item -> item.copy( stock_quantity = item.stock_quantity.takeIf { it.isNotEmpty() } ?: "0", cart_quantity = item.cart_quantity.takeIf { it.isNotEmpty() } ?: "0", product_price = item.product_price.takeIf { it.isNotEmpty() } ?: "0.0" ) } }
内容的提问来源于stack exchange,提问作者Adewale
相关产品推荐
相关产品推荐

