Search code examples
javaandroidpaypal-sandbox

java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NumberFormatException: For input string: "4.90"


Im following a tutorial for a food order app, and I add integrated PayPal Payment. So if I click on my FButton:

alertDialog.setPositiveButton("Abschicken", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //get comment adress from alert Dialog
            adress = edtAddress.getText().toString();
            comment = edtComment.getText().toString();

            String formatAmount = txtTotalPrice.getText().toString()
                                    .replace("€","")
                                    .replace(",","")
                                    .replaceAll("\\s+","");

            PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(formatAmount),"EUR","Pizza App Order", PayPalPayment.PAYMENT_INTENT_SALE);
            Intent intent = new Intent (getApplicationContext(), PaymentActivity.class);
            intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
            intent.putExtra(PaymentActivity.EXTRA_PAYMENT,payPalPayment);
            startActivityForResult(intent,PAYPAL_REQUEST_CODE);

            }


        });


    alertDialog.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            dialog.dismiss();
        }
    });

    alertDialog.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == PAYPAL_REQUEST_CODE)
    {
        if (resultCode == RESULT_OK)
        {
            PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if(confirmation != null)
            {
                try
                {
                    String paymentDetail = confirmation.toJSONObject().toString(4);
                    JSONObject jsonObject = new JSONObject(paymentDetail);


                    //CREATE NEW REQUEST
                    Request request = new Request(
                            Common.currentUser.getPhone(),
                            Common.currentUser.getName(),
                            adress,
                            txtTotalPrice.getText().toString(),
                            "0",
                            comment,
                            jsonObject.getJSONObject("response").getString("state"),
                            cart
                    );

                    //Submit to Firebase
                    requests.child(String.valueOf(System.currentTimeMillis()))
                            .setValue(request);
                    //DeleteCart
                    new Database(getBaseContext()).cleanCart();
                    Toast.makeText(Cart.this, "Vielen Dank! Ihre Bestellung wurde soeben abgeschickt!", Toast.LENGTH_SHORT).show();
                    finish();


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        else if (resultCode == Activity.RESULT_CANCELED)
            Toast.makeText(this, "Zahlung abgebrochen!", Toast.LENGTH_SHORT).show();
        else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
            Toast.makeText(this, "Fehler!", Toast.LENGTH_SHORT).show();
    }
}

private void loadListFood() {
    cart = new Database(this).getCarts();
    adapter = new CartAdapter(cart, this);
    adapter.notifyDataSetChanged();
    recyclerView.setAdapter(adapter);

    //Calculate total
    int total = 0;
    for (Order order:cart)
        total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
    Locale locale = new Locale("de", "DE");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    txtTotalPrice.setText(fmt.format(total));

}

I got this crash error:

E/AndroidRuntime: FATAL EXCEPTION: main Process: de.pizza, PID: 29841 java.lang.RuntimeException: Unable to start activity ComponentInfo{de.pizza/de.pizza.Cart}: java.lang.NumberFormatException: For input string: "4.90" at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6944) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) Caused by: java.lang.NumberFormatException: For input string: "4.90" at java.lang.Integer.parseInt(Integer.java:608) at java.lang.Integer.parseInt(Integer.java:643) at de.pizza.Cart.loadListFood(Cart.java:212) at de.pizza.Cart.onCreate(Cart.java:102) at android.app.Activity.performCreate(Activity.java:7174) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6944)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

I tried first to use "," in my prices, but same resuelt but in error code

For input string: "4,90"

If I remove all "." or ",", and I will have a total of 8€, I will get in PayPal Sandbox a total price of 800€.

If this could be useful to help me to solve my problem:

CartAdapter.java

 @Override
public void onBindViewHolder(@NonNull CartViewHolder holder, int position) {
    TextDrawable drawable = TextDrawable.builder()
            .buildRound(""+listData.get(position).getQuantity(), Color.RED);
    holder.img_cart_count.setImageDrawable(drawable);

    Locale locale = new Locale("de", "DE");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
    int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));
    holder.txt_price.setText(fmt.format(price));
    holder.txt_cart_name.setText(listData.get(position).getProductName());
}

UPDATE

Changed Integer.parseInt to Double.parseDouble

Result: If I use decimal prices, total price is Integer.

Like: Is 4.10€+4.00=8.00€ or 8.90€+4.50=12.00€ should 4.10€+4.00=8.10€ or 8.90€+4.50=13.40€

Actual Code:

Cart.java

alertDialog.setPositiveButton("Abschicken", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //get comment adress from alert Dialog
            adress = edtAddress.getText().toString();
            comment = edtComment.getText().toString();

            String formatAmount = txtTotalPrice.getText().toString()
                                    .replace("€","")
                                    .replace(",",".")
                                    .replaceAll("\\s+","");

            PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(formatAmount),"EUR","Pizzeria Bacco Usingen App Order", PayPalPayment.PAYMENT_INTENT_SALE);
            Intent intent = new Intent (getApplicationContext(), PaymentActivity.class);
            intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
            intent.putExtra(PaymentActivity.EXTRA_PAYMENT,payPalPayment);
            startActivityForResult(intent,PAYPAL_REQUEST_CODE);

            }


        });


    alertDialog.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            dialog.dismiss();
        }
    });

    alertDialog.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == PAYPAL_REQUEST_CODE)
    {
        if (resultCode == RESULT_OK)
        {
            PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if(confirmation != null)
            {
                try
                {
                    String paymentDetail = confirmation.toJSONObject().toString(4);
                    JSONObject jsonObject = new JSONObject(paymentDetail);


                    //CREATE NEW REQUEST
                    Request request = new Request(
                            Common.currentUser.getPhone(),
                            Common.currentUser.getName(),
                            adress,
                            txtTotalPrice.getText().toString(),
                            "0",
                            comment,
                            jsonObject.getJSONObject("response").getString("state"),
                            cart
                    );

                    //Submit to Firebase
                    requests.child(String.valueOf(System.currentTimeMillis()))
                            .setValue(request);
                    //DeleteCart
                    new Database(getBaseContext()).cleanCart();
                    Toast.makeText(Cart.this, "Vielen Dank! Ihre Bestellung wurde soeben abgeschickt!", Toast.LENGTH_SHORT).show();
                    finish();


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        else if (resultCode == Activity.RESULT_CANCELED)
            Toast.makeText(this, "Zahlung abgebrochen!", Toast.LENGTH_SHORT).show();
        else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
            Toast.makeText(this, "Fehler!", Toast.LENGTH_SHORT).show();
    }
}

private void loadListFood() {
    cart = new Database(this).getCarts();
    adapter = new CartAdapter(cart, this);
    adapter.notifyDataSetChanged();
    recyclerView.setAdapter(adapter);

    //Calculate total
    int total = 0;
    for (Order order:cart)
        total+=(Double.parseDouble(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
    Locale locale = new Locale("de", "DE");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);

    txtTotalPrice.setText(fmt.format(total));

}

CartAdapter.java

@Override
public void onBindViewHolder(@NonNull CartViewHolder holder, int position) {
    TextDrawable drawable = TextDrawable.builder()
            .buildRound(""+listData.get(position).getQuantity(), Color.RED);
    holder.img_cart_count.setImageDrawable(drawable);

    Locale locale = new Locale("de", "DE");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
    double price = (Double.parseDouble(listData.get(position).getPrice()))*(Double.parseDouble(listData.get(position).getQuantity()));
    //int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));
    holder.txt_price.setText(fmt.format(price));
    holder.txt_cart_name.setText(listData.get(position).getProductName());
}

Solution

  • You are parsing 4.90 which is not an Integer, so you of course can't parse it as Integer.

    Either use Double.parseDouble or Float.parseFloat instead.