在显示对象数组中的所有值时遇到问题

时间:2019-01-26 15:53:23

标签: javascript android parse-platform back4app

我正在使用云代码在Parse.com中集成Stripe付款,并在Android应用程序中使用Back4App。我正在用javascript编写云代码,但在显示结帐购物车中所有查询的结果时遇到了一些问题。

现在,我只是尝试检索每个cartItem并打印出其项目名称。但是最终,当用户单击购买时,我试图更新数据库中的每个项目数量。

例如:

  • 用户1有购物车商品:数量2的商品为10美元,数量2的商品B为8美元。

  • user2有购物车商品:数量为2的itemA,价格为$ 10。

  • 在parse.com数据库中,它显示总订单数为4的项目A和总订单数为2的项目B。

我已经在parse.com中创建了数据库,并为我的应用程序编写了Java代码,但是我无法理解如何编写云代码以及如何遍历每个购物车商品。

对不起,如果代码错误。我几乎在自学如何编程,而javascript对我来说是全新的。如果可以的话,请向我指出正确的方向,我相信其余的我都会弄清楚。谢谢。

现在,在我的user1购物车中,我有cartItems [steak,curry]。但是,当我运行云代码时,它仅显示咖喱而不显示牛排。我希望它显示购物车中的所有物品

我的设置方法是CartActivity.java中的一个按钮,它将数据发送到paymentActivity.java。在PaymentActivity.java内部,是我处理云代码的地方。

CartActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class CartActivity extends AppCompatActivity {

    ArrayList<String> myCartItems;
    ArrayList<String> myCartItemQuantity;
    ArrayList<String> myCartItemPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        displayCart();

    }

    private void displayCart() {
        // recieving data from MainActivity.class
        myCartItems = getIntent().getExtras().getStringArrayList("cartItems");
         myCartItemQuantity = getIntent().getExtras().getStringArrayList("itemQuantities");
        myCartItemPrice = getIntent().getExtras().getStringArrayList("itemPrices");

        Log.i("myCart ", "items: " + String.valueOf(myCartItems) + "\n" +
                "itemPrices: " + String.valueOf(myCartItemPrice) + "\n" +
                "itemQuantity: " + String.valueOf(myCartItemQuantity));

        LinearLayout linearLayoutVert = findViewById(R.id.linearLayout);
        for (int i = 0; i < myCartItems.size(); i++) {
            LinearLayout linearLayoutHor = new LinearLayout(getApplicationContext());
            linearLayoutHor.setOrientation(LinearLayout.HORIZONTAL);
            linearLayoutVert.addView(linearLayoutHor);

            TextView itemQuantity = new TextView(getApplicationContext());
            TextView item = new TextView(getApplicationContext());
            TextView itemPrice = new TextView(getApplicationContext());

            linearLayoutHor.addView(itemQuantity);
            linearLayoutHor.addView(item);
            linearLayoutHor.addView(itemPrice);

            itemQuantity.setText(myCartItemQuantity.get(i));
            item.setText(myCartItems.get(i));
            itemPrice.setText(myCartItemPrice.get(i));

            //ImageView Setup
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ic_trash);
            linearLayoutHor.addView(imageView);

        }
    }



public void toPaymentGateway(View view) {
        Intent paymentIntent = new Intent(getApplicationContext(), paymentActivity.class);
        paymentIntent.putExtra("cartItems", myCartItems);
        paymentIntent.putExtra("cartItemPrice", myCartItemPrice);
        paymentIntent.putExtra("cartItemQuantity", myCartItemQuantity);
        startActivity(paymentIntent);
    }

}

paymentActivity.java

package com.example.a1994m.doorstepsdelivery;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.parse.FunctionCallback;
import com.parse.Parse;
import com.parse.ParseCloud;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.stripe.android.Stripe;
import com.stripe.android.TokenCallback;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;

import java.util.ArrayList;
import java.util.HashMap;

import static com.example.a1994m.doorstepsdelivery.TestStripe.BACK4PAPP_API;
import static com.example.a1994m.doorstepsdelivery.TestStripe.CLIENT_KEY;

public class paymentActivity extends AppCompatActivity {

    ArrayList<String> myCartItems;
    ArrayList<String> myCartItemQuantity;
    ArrayList<String> myCartItemPrice ;
    ParseUser currentUser = ParseUser.getCurrentUser();

    public static final String PUBLISHABLE_KEY = "_________";
    public static final String APPLICATION_ID = "____________";
    public static final String CLIENT_KEY = "_____________";
    public static final String BACK4PAPP_API = "https://parseapi.back4app.com/";
    private Card card;
    private ProgressDialog progress;
    private Button purchase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);

        // Connect to Your Back4app Account
        Parse.initialize(new Parse.Configuration.Builder(this)
                .applicationId(APPLICATION_ID)
                .clientKey(CLIENT_KEY)
                .server(BACK4PAPP_API).build());
        Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE);

//         Create a demo test credit Card
//         You can pass the payment form data to create a Real Credit card
//         But you need to implement youself.

        card = new Card(
                "344776435490016", //card number
                05, //expMonth
                2021,//expYear
                "216"//cvc
        );
        progress = new ProgressDialog(this);
        purchase = (Button) findViewById(R.id.purchase);
        purchase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                buy();
                charge();
                Log.i("redirecting...", "BUTTON HAS BEEN CLICKED");
            }
        });

        // recieving data from CartActivity.class
         myCartItems = getIntent().getExtras().getStringArrayList("cartItems");
         myCartItemQuantity = getIntent().getExtras().getStringArrayList("cartItemQuantity");
         myCartItemPrice = getIntent().getExtras().getStringArrayList("cartItemPrice");

        Log.i("PaymentGateItems ", "items: " + String.valueOf(myCartItems) + "\n" +
                "itemPrices: " + String.valueOf(myCartItemPrice) + "\n" +
                "itemQuantity: " + String.valueOf(myCartItemQuantity));
    }

//    public void placeOrder(View view){
//
//        Intent stripeIntent = new Intent(getApplicationContext(), TestStripe.class);
//        startActivity(stripeIntent);
//    }

//    private void buy(){
//        boolean validation = card.validateCard();
//        if(validation){
//            startProgress("Validating Credit Card");
//            new Stripe(this).createToken(
//                    card,
//                    PUBLISHABLE_KEY,
//                    new TokenCallback() {
//                        @Override
//                        public void onError(Exception error) {
//                            Log.d("Stripe",error.toString());
//                        }
//
//                        @Override
//                        public void onSuccess(Token token) {
//                            finishProgress();
//                            charge(token);
//                        }
//                    });
//        } else if (!card.validateNumber()) {
//            Log.d("Stripe","The card number that you entered is invalid");
//        } else if (!card.validateExpiryDate()) {
//            Log.d("Stripe","The expiration date that you entered is invalid");
//        } else if (!card.validateCVC()) {
//            Log.d("Stripe","The CVC code that you entered is invalid");
//        } else {
//            Log.d("Stripe","The card details that you entered are invalid");
//        }
//    }

//    private void charge(Token cardToken){
//        HashMap<String, Object> params = new HashMap<String, Object>();
//
//        Log.i("items: ", String.valueOf(myCartItems));
//
//        params.put("quantity", myCartItemQuantity);
//        params.put("price", myCartItemPrice);
//        params.put("ItemName", myCartItems);
////        params.put("ItemName", "Pancake");
//        params.put("cardToken", cardToken.getId());
//        params.put("name",currentUser.getUsername());
////        params.put("name","Dominic Wong");
//        params.put("email",currentUser.getEmail());
////        params.put("email","dominwong4@gmail.com");
//        params.put("address","HIHI"); // needs input from billing address on card
//        params.put("zip","99999"); // needs input from billing address on card
//        params.put("city_state","CA"); // needs input from billing addresss on card
//        startProgress("Purchasing Item");
//        ParseCloud.callFunctionInBackground("purchaseItem", params, new FunctionCallback<Object>() {
//            public void done(Object response, ParseException e) {
//                finishProgress();
//                if (e == null) {
//                    Log.d("Cloud Response", "There were no exceptions! " + response.toString());
//                    Toast.makeText(getApplicationContext(),
//                            "Item Purchased Successfully ",
//                            Toast.LENGTH_LONG).show();
//                } else {
//                    Log.d("Cloud Response", "Exception: " + e);
//                    Toast.makeText(getApplicationContext(),
//                            e.getMessage().toString(),
//                            Toast.LENGTH_LONG).show();
//                }
//            }
//        });
//    }

    private void charge(){
        HashMap<String, Object> params = new HashMap<String, Object>();

        Log.i("items: ", String.valueOf(myCartItems));

        params.put("quantity", myCartItemQuantity);
        params.put("price", myCartItemPrice);
        params.put("ItemName", myCartItems);
//        params.put("ItemName", "Pancake");
//        params.put("cardToken", cardToken.getId());
        params.put("name",currentUser.getUsername());
//        params.put("name","Dominic Wong");
        params.put("email",currentUser.getEmail());
//        params.put("email","dominwong4@gmail.com");
        params.put("address","HIHI"); // needs input from billing address on card
        params.put("zip","99999"); // needs input from billing address on card
        params.put("city_state","CA"); // needs input from billing addresss on card
        startProgress("Purchasing Item");
        ParseCloud.callFunctionInBackground("purchaseItem", params, new FunctionCallback<Object>() {
            public void done(Object response, ParseException e) {
                finishProgress();
                if (e == null) {
                    Log.d("Cloud Response", "There were no exceptions! " + response.toString());
                    Toast.makeText(getApplicationContext(),
                            "Item Purchased Successfully ",
                            Toast.LENGTH_LONG).show();
                } else {
                    Log.d("Cloud Response", "Exception: " + e);
                    Toast.makeText(getApplicationContext(),
                            e.getMessage().toString(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void startProgress(String title){
        progress.setTitle(title);
        progress.setMessage("Please Wait");
        progress.show();
    }

    private void finishProgress(){
        progress.dismiss();
    }
}

云代码:

var Stripe = require("stripe")("sk_test_rU8GCiz0tkNB02ZbcsXP3b2a");
Parse.Cloud.define("purchaseItem", function (request, response) {
    var item, order;
    var total = 0;

    var CartItems = request.params.ItemName;
    var CartPrice = request.params.price;
    var CartItemQuantity = request.params.quantity;

    var cartQuery = new Parse.Query('Item');

    for(var i=0; i<CartItems.length; i++){

        cartQuery.equalTo('ItemName', CartItems[i]);

        cartQuery.find()
            .then(function (results) {
                for (var result of results) {
                    response.success("got the items " + 
                    result.get("ItemName"));
                }
            })
            .catch(function (error) {
                response.error("could not get the items " + error);
            });
    }
});

1 个答案:

答案 0 :(得分:1)

您应该只拨打一次https://us-central1-<projectid>.cloudfunctions.net/sendMailFunction。随后的呼叫将被忽略。 您可以尝试这样的事情。

sendEmail() {

    let url = `https://your-cloud-function-url/function`
    let params: URLSearchParams = new URLSearchParams();
    let headers = new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });

    params.set('to', 'user@example.com');
    params.set('from', 'you@yoursupercoolapp.com');
    params.set('subject', 'test-email');
    params.set('content', 'Hello World');

    return this.http.post(url, params, headers)
                    .toPromise()
                    .then( res => {
                      console.log(res)
                    })
                    .catch(err => {
                      console.log(err)
                    })

  }

这将以数组形式显示项目。 例如response.success 然后,您应该在客户端进行处理。例如使用cartQuery.find() .then(function (results) { var items = []; for (var result of results) { items.push(result.get("ItemName")); } response.success(JSON.stringify(items)); }) .catch(function (error) { response.error("could not get the items " + error); });

相关问题