簡體   English   中英

如何在我的代碼中為空字符串賦值以防止 NumberFormatException

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

我有一個 NumberFormatException,這可能是由於在產品和購物車數據 class 中將一個空字符串傳遞給 product_quantity。 在將代碼解析為 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)

這是調試控制台引用的成功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
    }
}

這是來自 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()
                }
            }
        }
}

這是產品數據 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

這是購物車數據 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

您可以使用toIntOrNull ,它在解析失敗時返回解析的Intnull 然后,使用let?. , 像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM