Issue
Hi I am trying to get value of a string into a integer type like bellow
private void updateTotalQuantity() {
int quantity = 0;
double price=0.0;
Double totalPrice = 0.0;
List<ProductDetail> products = mProductsAdapter.getProducts();
for (ProductDetail product : products) {
if (product.getQuantity() != null)
{
quantity += (Integer.parseInt(product.getQuantity()));
}
if (product.getPrice()!=null && product.getQuantity() != null)
{
price = Double.parseDouble(product.getPrice());
totalPrice = totalPrice + (price * Double.parseDouble(product.getQuantity()));
}
}
totalQty.setText(String.valueOf(quantity));
totalOrder.setText(String.valueOf(totalPrice));
}
When I run my application the app crashes at point quantity += (Integer.parseInt(product.getQuantity()));
with execption message
java.lang.NumberFormatException: For input string: "null"
How can I get rid of this ?
Any help would be highly appreciated.
Solution
You are doing a null-check in
if (product.getQuantity() != null)
but your string is initialized and its value actually is "null"
as a string. Wherever your data is coming from, the Adapter most likely parses empty fields into "null"
instead of null
.
Either, you check against "null"
, too:
if (product.getQuantity() != null && product.getQuantity() != "null")
or you change the adapter so that it actually returns null
on an empty field.
Answered By - Torge Rosendahl
Answer Checked By - Katrina (JavaFixing Volunteer)