简体   繁体   English

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

[英]Having problems displaying all values in array of objects

I am working on using cloud code to integrate Stripe payment in Parse.com and using Back4App for my android app. 我正在使用云代码在Parse.com中集成Stripe付款,并在Android应用程序中使用Back4App。 I am writing the cloud code in javascript and I'm having some issues displaying all my queried results from the checkout cart. 我正在用JavaScript编写云代码,但在显示结帐购物车中所有查询结果时遇到一些问题。

For now, I am just trying to retrieve each cartItem and print out its item name. 现在,我只是尝试检索每个cartItem并打印出其项目名称。 But eventually, I am trying to update each item quantity in the database when the user has clicked buy. 但是最终,当用户单击购买时,我试图更新数据库中的每个项目数量。

For example: 例如:

  • user1 has cart items: item A with quantity 2 for $10 and item B with quantity 2 for $8. user1有购物车商品:数量2的商品为$ 10,数量为2的商品B为$ 8。

  • user2 has cart items: itemA with quantity 2 for $10. user2有购物车项目:数量为2的itemA为$ 10。

  • In the parse.com database, it shows item A with total orders as 4 and item B with total orders of 2. 在parse.com数据库中,它显示总订单数为4的项目A和总订单数为2的项目B。

I've already created my database in parse.com and have written the java code for my app but I'm failing to understand how to write cloud code and looping through each cart item. 我已经在parse.com中创建了数据库,并为我的应用程序编写了Java代码,但是我无法理解如何编写云代码以及如何遍历每个购物车项目。

I am sorry if the code is bad. 如果代码不好,我很抱歉。 I'm pretty much teaching myself how to program and javascript is completely new to me. 我几乎在自学如何编程,而javascript对我来说是全新的。 If you could please point me in the right direction, I am sure I will figure the rest out. 如果可以的话,请向我指出正确的方向,我相信其余的我都会弄清楚。 Thank you. 谢谢。

Right now, in my cart for user1 I have cartItems[steak, curry]. 现在,在用户1的购物车中,我有cartItems [steak,curry]。 But when i run the cloud code, it is displaying only curry and not steak. 但是,当我运行云代码时,它仅显示咖喱而不显示牛排。 I want it to display all the items in the cart 我希望它显示购物车中的所有物品

The way I have it set up is a button from CartActivity.java sends data over to paymentActivity.java. 我设置的方式是CartActivity.java中的一个按钮,它将数据发送到paymentActivity.java。 And inside paymentActivity.java is where I process the cloud code. 在paymentActivity.java内部,是我处理云代码的地方。

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

Cloud Code: 云代码:

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

You should only call response.success once. 您应该只调用一次response.success Subsequent calls will be ignored. 随后的呼叫将被忽略。 You can try something like this. 您可以尝试这样。

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

This will respond with the items in an array form. 这将以数组形式响应项目。 eg ["steak", "curry"] You should then process this in the client side. 例如["steak", "curry"]然后应在客户端进行处理。 eg using JSONArray 例如使用JSONArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM