java.lang.RuntimeException:无法启动活动ComponentInfo:java.lang.NumberFormatException:对于输入字符串:“ 4.90”

时间:2019-01-10 12:18:03

标签: java android paypal-sandbox

我正在遵循食品订单应用程序的教程,并添加了集成的PayPal付款。因此,如果我单击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));

}

我遇到此崩溃错误:

  

E / Android运行时:致命异常:主要       流程:de.pizza,PID:29841       java.lang.RuntimeException:无法启动活动ComponentInfo {de.pizza/de.pizza.Cart}:java.lang.NumberFormatException:对于输入字符串:“ 4.90”           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)           在android.app.ActivityThread.-wrap11(未知来源:0)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1696)           在android.os.Handler.dispatchMessage(Handler.java:105)           在android.os.Looper.loop(Looper.java:164)           在android.app.ActivityThread.main(ActivityThread.java:6944)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:327)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)        原因:java.lang.NumberFormatException:对于输入字符串:“ 4.90”           在java.lang.Integer.parseInt(Integer.java:608)           在java.lang.Integer.parseInt(Integer.java:643)           在de.pizza.Cart.loadListFood(Cart.java:212)           在de.pizza.Cart.onCreate(Cart.java:102)           在android.app.Activity.performCreate(Activity.java:7174)           在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)           在android.app.ActivityThread.-wrap11(未知来源:0)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1696)           在android.os.Handler.dispatchMessage(Handler.java:105)           在android.os.Looper.loop(Looper.java:164)           在android.app.ActivityThread.main(ActivityThread.java:6944)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:327)           com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

我首先尝试在价格中使用“,”,但使用相同的代码,但错误代码

  

对于输入字符串:“ 4,90”

如果我删除所有“。”或“,”,我总共有8欧元,在PayPal Sandbox中获得的总价为800欧元。

如果这可以帮助我解决问题,

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());
}

更新

  

Integer.parseInt更改为Double.parseDouble

结果: 如果我使用十进制价格,则总价格为整数。

赞: 是4.10€+ 4.00 = 8.00€或8.90€+ 4.50 = 12.00€ 应该为4.10€+ 4.00 = 8.10€或8.90€+ 4.50 = 13.40€

实际代码:

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());
}

3 个答案:

答案 0 :(得分:3)

您正在解析不是整数的4.90,因此您当然不能将其解析为整数。

请改用Double.parseDoubleFloat.parseFloat

答案 1 :(得分:0)

Integer.parseInt不应包含“,”

来自:https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

将字符串参数解析为带符号的十进制整数。字符串中的字符都必须全部为十进制数字,但第一个字符可以是表示负值的ASCII减号'-'('\ u002D'),也可以是ASCII加号'+'('\ u002B')表示正值。返回所得的整数值,就像将参数和基数10作为parseInt(java.lang.String,int)方法的参数一样。

答案 2 :(得分:0)

更改此行:

int price = (Integer.parseInt(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));

对此:

double price = (Double.parseDouble(listData.get(position).getPrice()))*(Integer.parseInt(listData.get(position).getQuantity()));