firebase实时数据库当我通过on-activityresult从其他活动传递时复制数据

kuuvgm7e  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(180)

我正在androidstudio中用java开发一个与firebase一起工作的应用程序。当我在radiogroup中选择选项“efectivo”即货到付款时,只在实时数据库中记录一个寄存器,但当我选择“paypal”或“tarjeta de credito”时,firebase寄存器重复。
这是我的密码:
cartfragment.java文件

builder.setPositiveButton("Si", (dialog, which) -> {
        //Toast.makeText(getContext(), "Implementar despues", Toast.LENGTH_SHORT).show();
        if (rdi_cod.isChecked()) {
            String finalPrice = txt_total_price.getText().toString()
                    .replace("Total: $", "");
            Double precioFinal = Double.valueOf(finalPrice);
            if (precioFinal <= 250)
                paymentCOD(edt_address.getText().toString(), edt_comment.getText().toString());
            else {
                AlertDialog.Builder builder2 = new AlertDialog.Builder(getContext())
                        .setTitle("Por el momento...")
                        .setMessage("En ordenes con pago en efectivo el monto máximo es de $250.");
                builder2.setPositiveButton("Ok", null);
                builder2.create().show();

            }
        } else if (rdi_paypal.isChecked()) {

            address = edt_address.getText().toString();
            comment = edt_comment.getText().toString();

            String finalPrice = txt_total_price.getText().toString()
                    .replace("Total: $", "");

            //Mostrar PayPal
            PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(finalPrice)
                    , "MXN"
                    , "HastaTuCasa Orden",
                    PayPalPayment.PAYMENT_INTENT_SALE);
            Intent intent = new Intent(getContext(), PaymentActivity.class);
            intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
            intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payPalPayment);
            startActivityForResult(intent, PAYPAL_REQUEST_CODE);

        } else if (rdi_stripe.isChecked()) {

            String finalPrice = txt_total_price.getText().toString()
                    .replace("Total: $", "");

            bundle.putString("finalPrice", finalPrice);

            Intent intent = new Intent(getContext(), CheckoutActivity.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, LAUNCH_SECOND_ACTIVITY);

        }
    });

    AlertDialog dialog = builder.create();
    dialog.show();
}

这是我对同一活动采用的货到付款方法:

private void paymentCOD(String address, String comment) {
    compositeDisposable.add(cartDataSource.getAllCart(Common.currentUser.getUid())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(cartItems -> {

                //Cuando tenemos todos los items del carrito obtenemos el precio total
                cartDataSource.sumPriceInCart(Common.currentUser.getUid())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new SingleObserver<Double>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onSuccess(Double totalPrice) {
                                Double finalPrice = totalPrice;
                                Order order = new Order();
                                order.setUserId(Common.currentUser.getUid());
                                order.setUserName(Common.currentUser.getName());
                                order.setUserPhone(Common.currentUser.getPhone());
                                order.setShippingAddress(address);
                                order.setComment(comment);

                                long estimatedServerTimeMs = System.currentTimeMillis();

                                SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd,yyyy HH:mm:ss");
                                Date resultDate = new Date(estimatedServerTimeMs);
                                Log.d("HORA_EXACTA", "" + sdf.format(resultDate));

                                if (currentLocation != null) {
                                    order.setLat(currentLocation.getLatitude());
                                    order.setLng(currentLocation.getLongitude());
                                } else {
                                    order.setLat((double) -0.1f);
                                    order.setLng((double) -0.1f);
                                }

                                order.setCartItemList(cartItems);
                                order.setTotalPayment(totalPrice);
                                order.setDiscount(0);
                                order.setFinalPayment(finalPrice);
                                order.setCod(true);
                                order.setTransactionId("Efectivo");
                                order.setStatus("Aprobado");

                                //Enviar la orden a Firebase
                                writeOrderToFirebase(order);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });

            }, throwable -> {
                Toast.makeText(getContext(), "" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
            }));
}

这是贝宝和信用卡的结果活动。

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PAYPAL_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirmation != null) {
                compositeDisposable.add(cartDataSource.getAllCart(Common.currentUser.getUid())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(cartItems -> {

                            //Cuando tenemos todos los items del carrito obtenemos el precio total
                            cartDataSource.sumPriceInCart(Common.currentUser.getUid())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new SingleObserver<Double>() {
                                        @Override
                                        public void onSubscribe(Disposable d) {

                                        }

                                        @Override
                                        public void onSuccess(Double totalPrice) {
                                            Double finalPrice = totalPrice;
                                            Order order = new Order();
                                            order.setUserId(Common.currentUser.getUid());
                                            order.setUserName(Common.currentUser.getName());
                                            order.setUserPhone(Common.currentUser.getPhone());
                                            order.setShippingAddress(address);
                                            order.setComment(comment);

                                            long estimatedServerTimeMs = System.currentTimeMillis();

                                            SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd,yyyy HH:mm:ss");
                                            Date resultDate = new Date(estimatedServerTimeMs);
                                            Log.d("HORA_EXACTA", "" + sdf.format(resultDate));

                                            order.setOrderTime(sdf.format(resultDate));

                                            if (currentLocation != null) {
                                                order.setLat(currentLocation.getLatitude());
                                                order.setLng(currentLocation.getLongitude());
                                            } else {
                                                order.setLat((double) -0.1f);
                                                order.setLng((double) -0.1f);
                                            }

                                            order.setCartItemList(cartItems);
                                            order.setTotalPayment(totalPrice);
                                            order.setDiscount(0);
                                            order.setFinalPayment(finalPrice);
                                            order.setCod(false);
                                            order.setTransactionId("PayPal");
                                            order.setStatus("Aprobado");

                                            //Enviar la orden a Firebase
                                            writeOrderToFirebase(order);

                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });

                        }, throwable -> {
                            Toast.makeText(getContext(), "" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }));
            }
        } else if (resultCode == Activity.RESULT_CANCELED)
            Toast.makeText(getContext(), "Pago cancelado", Toast.LENGTH_SHORT).show();
        else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
            Toast.makeText(getContext(), "Pago no valido", Toast.LENGTH_SHORT).show();
    }

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if (resultCode == Activity.RESULT_OK) {
            compositeDisposable.add(cartDataSource.getAllCart(Common.currentUser.getUid())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(cartItems -> {

                        //Cuando tenemos todos los items del carrito obtenemos el precio total
                        cartDataSource.sumPriceInCart(Common.currentUser.getUid())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new SingleObserver<Double>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onSuccess(Double totalPrice) {
                                        Double finalPrice = totalPrice;
                                        Order order = new Order();
                                        order.setUserId(Common.currentUser.getUid());
                                        order.setUserName(Common.currentUser.getName());
                                        order.setUserPhone(Common.currentUser.getPhone());
                                        order.setShippingAddress(address);
                                        order.setComment(comment);

                                        long estimatedServerTimeMs = System.currentTimeMillis();

                                        SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd,yyyy HH:mm:ss");
                                        Date resultDate = new Date(estimatedServerTimeMs);
                                        Log.d("HORA_EXACTA", "" + sdf.format(resultDate));

                                        order.setOrderTime(sdf.format(resultDate));

                                        if (currentLocation != null) {
                                            order.setLat(currentLocation.getLatitude());
                                            order.setLng(currentLocation.getLongitude());
                                        } else {
                                            order.setLat((double) -0.1f);
                                            order.setLng((double) -0.1f);
                                        }

                                        order.setCartItemList(cartItems);
                                        order.setTotalPayment(totalPrice);
                                        order.setDiscount(0);
                                        order.setFinalPayment(finalPrice);
                                        order.setCod(false);
                                        order.setTransactionId("Tarjeta");
                                        order.setStatus("Aprobado");

                                        //Enviar la orden a Firebase
                                        writeOrderToFirebase(order);

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                });

                    }, throwable -> {
                        Toast.makeText(getContext(), "" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                    }));
        } else if (resultCode == Activity.RESULT_CANCELED)
            Toast.makeText(getContext(), "Pago no aprobado", Toast.LENGTH_SHORT).show();
    }
}

}
这是checkoutactivity.java的信用卡成功交易

private final class PaymentResultCallback
        implements ApiResultCallback<PaymentIntentResult> {
    @NonNull
    private final WeakReference<CheckoutActivity> activityRef;

    PaymentResultCallback(@NonNull CheckoutActivity activity) {
        activityRef = new WeakReference<>(activity);
    }

    @Override
    public void onSuccess(@NonNull PaymentIntentResult result) {
        final CheckoutActivity activity = activityRef.get();
        if (activity == null) {
            return;
        }
        PaymentIntent paymentIntent = result.getIntent();
        PaymentIntent.Status status = paymentIntent.getStatus();
        if (status == PaymentIntent.Status.Succeeded) {
            // Payment completed successfully

            Toast.makeText(activity, "Pago procesado exitosamente", Toast.LENGTH_SHORT).show();

            Intent returnIntent = new Intent(getApplicationContext(), CartFragment.class);
            setResult(Activity.RESULT_OK, returnIntent); //This is the important part.
            finish();

        } else if (status == PaymentIntent.Status.RequiresPaymentMethod) {
            // Payment failed – allow retrying using a different payment method
            Toast.makeText(activity, "No pudimos procesar tu pago, por favor ingresa una tarjeta válida", Toast.LENGTH_SHORT).show();

            Intent returnIntent = new Intent(getApplicationContext(), CartFragment.class);
            setResult(Activity.RESULT_CANCELED, returnIntent); //This is the important part.
            finish();

        }
    }

最后是在firebase中注册数据的方法:

private void writeOrderToFirebase(Order order) {

    FirebaseDatabase.getInstance()
            .getReference(Common.ORDER_REF)
            .child(Common.createOrderNumber())
            .setValue(order)
            .addOnFailureListener(e -> {
                Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
            }).addOnCompleteListener(task -> {
        //Cuando la orden sea exitosa
        cartDataSource.cleanCart(Common.currentUser.getUid())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(Integer integer) {
                        //Resultado exitoso
                        Toast.makeText(getContext(), "Orden completada exitosamente!", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().postSticky(new CounterCartEvent(true));
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    });
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题