简体   繁体   English

如何在我的代码中为空字符串赋值以防止 NumberFormatException

[英]How do I assign a value to an empty string in my code to prevent NumberFormatException

I'm having a NumberFormatException which is likely due passing an empty string to product_quantity in the product and cart data class.我有一个 NumberFormatException,这可能是由于在产品和购物车数据 class 中将一个空字符串传递给 product_quantity。 I'm having difficulty assigning value to the product_quantity in my code before parsing it toInt()在将代码解析为 int() 之前,我很难为代码中的 product_quantity 赋值

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hardextech.store, PID: 22948
java.lang.NumberFormatException: For input string: ""
    at java.lang.Integer.parseInt(Integer.java:627)
    at java.lang.Integer.parseInt(Integer.java:650)
    at com.hardextech.store.ui.activities.ui.activities.CartListActivity.successfullyGetTheCartItemList(CartListActivity.kt:90)
    at com.hardextech.store.firestore.FirestoreClass.getCartList$lambda-28(FirestoreClass.kt:493)
    at com.hardextech.store.firestore.FirestoreClass.$r8$lambda$Uc6EU1OaDQc7HeKgs7cM5uEsC2A(Unknown Source:0)
    at com.hardextech.store.firestore.FirestoreClass$$ExternalSyntheticLambda12.onSuccess(Unknown Source:4)
    at com.google.android.gms.tasks.zzn.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6819)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

This is the successfullyGetCartTheCartItemList method referenced from the debugging console这是调试控制台引用的成功GetCartTheCartItemList方法

 fun successfullyGetTheCartItemList(listOfItemInTheCart: ArrayList<Cart>){
    dismissProgressDialogue()
    // checking for the product list in the stock-- determining if the product is available in the stock
    for (everyProductInTheProductList in mProductList){
        for (everyProductInTheCart in listOfItemInTheCart){
            if (everyProductInTheProductList.product_id == everyProductInTheCart.product_id){
                everyProductInTheCart.product_quantity = everyProductInTheProductList.product_quantity

                // if there are no products in the stock
                if (everyProductInTheProductList.product_quantity.toInt() == 0){
                    everyProductInTheCart.cart_quantity = everyProductInTheProductList.product_quantity
                }
            }
        }
    }
    // initializing the mCartDataClassDetails
    mCartDataClassDetails = listOfItemInTheCart

    // checking for the product list in the cart
    if (mCartDataClassDetails.size >0){
        rv_cart_item_list.visibility = View.VISIBLE
        ll_check_out.visibility = View.VISIBLE
        tv_no_cart_item_found.visibility = View.GONE

        rv_cart_item_list.layoutManager = LinearLayoutManager(this)
        rv_cart_item_list.setHasFixedSize(true)
        // create an adapter variable for the recycler view
        val cartListAdapter = CartItemListAdapter(this, listOfItemInTheCart)
        // pass the adapter to the recyclerview
        rv_cart_item_list.adapter = cartListAdapter
        // assign double to the sub-total in the itemListCart
        var subTotal: Double = 0.0
        // run through all product in the list
        for (everyItemInTheCart in mCartDataClassDetails){
            // checking for the available quantity of product
               val availableProductQuantity = everyItemInTheCart.product_quantity.toInt()
            if (availableProductQuantity > 0){
                    Log.i("Cart Title", everyItemInTheCart.product_title)
                    // convert the price to Double
                    val price = everyItemInTheCart.product_price.toDouble()
                    // convert the quantity to Int
                    val quantity = everyItemInTheCart.cart_quantity.toInt()
                    // calculate the sub-total cost
                    subTotal+=(price*quantity)
                }

        }
        // assign the value of the sub total for each product sales
        tv_product_subTotal.text = "NGN $subTotal"
        // assigning the delivery cost for each product sales
        // TODO: Seek for API to calculate the delivery cost for each product and/or write the code criteria for calculating it
        tv_delivery_cost.text = (subTotal*0.05).toString()

        if (subTotal > 0){
            ll_check_out.visibility = View.VISIBLE
            // TODO: Change the logic for the delivery cost
            val totalProductCost = subTotal + (subTotal*0.05)
            tv_total_product_cost.text = "NGN $totalProductCost"
        } else{
            ll_check_out.visibility = View.GONE
        }
    } else{
        rv_cart_item_list.visibility = View.GONE
        ll_check_out.visibility = View.GONE
        tv_no_cart_item_found.visibility = View.VISIBLE
    }
}

This is method from the Firestore class这是来自 Firestore class 的方法

 fun getCartList(activity: Activity){
    // the method for downloading the cart item list
    mFireStore.collection(Constants.CART_ITEMS_COLLECTION)
            // get the cart items for the logged in user
        .whereEqualTo(Constants.USER_ID, getCurrentUserID())
        .get()

        .addOnSuccessListener { document->
            Log.i(activity.javaClass.simpleName, document.documents.toString())
            // get the list of the cart items--- number of products in the cart
            val listOfCartItems: ArrayList<Cart> = ArrayList()
            // run through each of the document(FireStore document field) in the list
            for (loopingThroughCartItems in document.documents){
                // converting the products in the cart to an object and surround with null check
                val cartItemListObject = loopingThroughCartItems.toObject(Cart::class.java)!!
                cartItemListObject.id= loopingThroughCartItems.id
                // add the result of the loop to the cart item arrayList
                listOfCartItems.add(cartItemListObject)
            }

            when(activity){
                is CartListActivity->{
                    activity.successfullyGetTheCartItemList(listOfCartItems)
                }

            }
        }.addOnFailureListener {e->
            Log.e(activity.javaClass.simpleName, " Error downloading products in the cart", e)
            when(activity){
                is CartListActivity->{
                    activity.dismissProgressDialogue()
                }
            }
        }
}

This is Product Data class这是产品数据 class

  @Parcelize
data class Product(
    val user_id: String = "",
    var id: String = "",
    val product_image: String = "",
    val product_title: String = "",
    val product_price: String = "",
    val product_description: String = "",
    val product_quantity: String = "",
    val user_name: String = "",
    var product_id:String =""

): Parcelable

This is the cart data class这是购物车数据 class

    @kotlinx.parcelize.Parcelize
data class Cart(
    val user_id: String = "",
    val product_id: String = "",
    val product_title: String = "",
    val product_image: String = "",
    val product_price: String = "",
    var cart_quantity: String = "",
    var product_quantity: String ="",
    var id: String = ""
): Parcelable

You can use toIntOrNull , which returns parsed Int or null when failed to parse.您可以使用toIntOrNull ,它在解析失败时返回解析的Intnull Then, use let with ?.然后,使用let?. , like this: , 像这样:

string.toIntOrNull()?.let { parsedInt ->
    // Your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM