如何从购物车中的每件商品中获取数量并传递给活动?

Posted

技术标签:

【中文标题】如何从购物车中的每件商品中获取数量并传递给活动?【英文标题】:How do I get the quantity from every item in cart and pass to an activity? 【发布时间】:2020-07-07 19:23:22 【问题描述】:

我有一个 cartactivity 和 Cartadapter,在 Cartadapter 中我为每个东西添加增量和减量,然后我将其与总价格和总重量相加并将其发送到活动(它通过将 textview 活动从 cartactivity 传递到 adapteractivity 来工作)现在我想获得每个项目的单独数量以格式发送到数据库示例如果项目是(钱包,包,鞋)然后将发送到数据库的数量像这样(2、3、3)2代表钱包和(,)用于分隔商品数量,3 代表包,3 代表鞋子。我不知道如何获取每个数量并以这样的格式发送

看看我的适配器


import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

import app.gify.co.id.R;
import app.gify.co.id.activity.List_Kado;
import app.gify.co.id.modal.MadolCart;

public class AdapterCart extends RecyclerView.Adapter<RecyclerView.ViewHolder> 

    ArrayList<MadolCart> carts;
    MadolCart mm;
    View view;
    View viewku;
    Context context;
    int kuantitas;
    String totalname;
    int totalBerat, totalharga;
    TextView totalhargas, totalberats;

    public AdapterCart(ArrayList<MadolCart> carts, Context context, TextView totalhargas, TextView totalberats) 
        this.carts = carts;
        this.context = context;
        this.totalhargas = totalhargas;
        this.totalberats = totalberats;
    

    public class MyCart extends RecyclerView.ViewHolder 

        public ImageView gambar, tambah, kurang;
        public TextView harga, nama, quantitas;
        public RelativeLayout background, foreground;
        public ElegantNumberButton quantity;

        public MyCart(@NonNull View itemView) 
            super(itemView);
            gambar = itemView.findViewById(R.id.gambarcart);
            tambah = itemView.findViewById(R.id.tambahcart);
            kurang = itemView.findViewById(R.id.kurangcart);
            harga = itemView.findViewById(R.id.hargacart);
            nama = itemView.findViewById(R.id.namacart);
            quantitas = itemView.findViewById(R.id.quantitas);
            background = itemView.findViewById(R.id.background);
            foreground = itemView.findViewById(R.id.foreground);
            quantity = itemView.findViewById(R.id.quantity);
        
    

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_cart, parent, false);
        viewku = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart, parent, false);
        return new MyCart(view);
    

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) 
        kuantitas = carts.get(position).getJumlah();
        int hargaku = carts.get(position).getHarga() * kuantitas;
        for (int a = 0; a < carts.size(); a++)
            Log.d("cartsizeku", "onBindViewHolder: " + carts.size()+ " s " + carts.get(a).getNamacart() + " s " + carts.get(a).getHarga());
            String nama = carts.get(position).getNamacart();
            if (nama.equals(carts.get(a).getNamacart()))
                totalhargas.setText(String.valueOf(totalCart(carts, carts.get(a).getNamacart())));
                totalberats.setText(String.valueOf(beratCart(carts, carts.get(a).getNamacart())));
            

        

        Locale locale = new Locale("id", "ID");
        NumberFormat format = NumberFormat.getCurrencyInstance(locale);

        ((MyCart)holder).harga.setText(format.format(Double.valueOf(hargaku)));
        ((MyCart)holder).nama.setText(carts.get(position).getNamacart());
        Glide.with(view).load(carts.get(position).getGambar()).into(((MyCart)holder).gambar);
        Intent intent = new Intent("message_subject_intent");
//        intent.putExtra("name", String.valueOf((totalCart(carts))));
        intent.putExtra("title", String.valueOf((getName(carts))));
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);


        ((MyCart) holder).tambah.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                int count = Integer.parseInt(((MyCart) holder).quantitas.getText().toString());
                if (count<9)
                    count+=1;
                    ((MyCart)holder).quantitas.setText(String.valueOf(count));
                    int harga = carts.get(position).getHarga()*count;
                    ((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
                    String nama = carts.get(position).getNamacart();
                    totalhargas.setText(String.valueOf(totalCart(carts, nama)));
                    totalberats.setText(String.valueOf(beratCart(carts, nama)));
                

//                ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
                int total = hargaku * kuantitas;
                Intent intents = new Intent("message_subject_intent");
                intents.putExtra("name", String.valueOf((getName(carts))));
                LocalBroadcastManager.getInstance(context).sendBroadcast(intents);
            
        );
        ((MyCart) holder).kurang.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                int count = Integer.parseInt(((MyCart)holder).quantitas.getText().toString());
                if (count>1)
                    count-=1;
                    ((MyCart)holder).quantitas.setText(String.valueOf(count));
                    int harga = carts.get(position).getHarga()*count;
                    ((MyCart)holder).harga.setText(String.valueOf(format.format(Double.valueOf(harga))));
                    String nama = carts.get(position).getNamacart();
                    totalhargas.setText(String.valueOf(kurangtotalcart(carts, nama)));
                    totalberats.setText(String.valueOf(kurangberatCart(carts, nama)));
                


//                ((MyCart)holder).quantitas.setText(String.valueOf(kuantitas));
                int total = hargaku * kuantitas;
                Intent intents = new Intent("message_subject_intent");
                intents.putExtra("name", String.valueOf((getName(carts))));
                LocalBroadcastManager.getInstance(context).sendBroadcast(intents);


            
        );
    

    @Override
    public int getItemCount() 
        return carts.size();
    

    public int totalCart(ArrayList<MadolCart> items, String name)

        for(int i = 0 ; i < items.size(); i++) 
            totalname = items.get(i).getNamacart();
            if (totalname.equals(name))
                totalharga += items.get(i).getHarga();
            
        
        return totalharga;
    
    public int kurangtotalcart(ArrayList<MadolCart> items, String name)

        for(int i = 0 ; i < items.size(); i++) 
            totalname = items.get(i).getNamacart();
            if (totalname.equals(name))
                totalharga -= items.get(i).getHarga();
            
        
        return totalharga;
    

    public int beratCart(ArrayList<MadolCart> items, String name)
        for(int i = 0 ; i < items.size(); i++) 
            totalname = items.get(i).getNamacart();
            if (totalname.equals(name))
                totalBerat += items.get(i).getBerat();
            
        
        return totalBerat;
    

    public int kurangberatCart(ArrayList<MadolCart> items, String name)
        for(int i = 0 ; i < items.size(); i++) 
            totalname = items.get(i).getNamacart();
            if (totalname.equals(name))
                totalBerat -= items.get(i).getBerat();
            
        
        return totalBerat;
    

    public String getName(List<MadolCart> name)

        String ku = "";
        for (int i = 0; i < name.size(); i++)
            ku += name.get(i).getNamacart() + ", ";
        

        return ku;
    

    public void removeItem(int item)
        carts.remove(item);

        notifyItemRemoved(item);
    

    public void restoreItem(MadolCart madolCart, int item)
        carts.add(item, madolCart);

        notifyItemInserted(item);
    

    public void quantityPlus(MadolCart madolCart, int item)


    


这是我的活动

package app.gify.co.id.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.DrawableImageViewTarget;
import com.google.android.material.navigation.NavigationView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;
import java.util.Random;

import app.gify.co.id.R;
import app.gify.co.id.adapter.AdapterCart;
import app.gify.co.id.modal.MadolCart;
//import app.gify.co.id.thirdparty.GMailSender;
//import app.gify.co.id.thirdparty.SenderAgent;
import app.gify.co.id.widgets.RecyclerTouchDelete;

import static app.gify.co.id.baseurl.UrlJson.DELETECART;
import static app.gify.co.id.baseurl.UrlJson.GETBARANG;
import static app.gify.co.id.baseurl.UrlJson.GETCART;

public class CartActivity extends AppCompatActivity implements RecyclerTouchDelete.RecyclerTouchListener

    Button Checkout, lanjutBelanja;
    ImageView backCart;
    TextView totalbelanjar, totalberat;
    AdapterCart adapterCart;
    ArrayList<MadolCart> madolCarts;
    String namacart, gambarcart, uidku;
    GridLayoutManager glm;
    RecyclerView recyclerView;
    MainActivity mainActivity;
    NavigationView navigationView;
    public int hargaku, beratku, kuantitas, lastNumber, idbarang, getHargaAwal;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    Spanned templateConvert;
    NumberFormat format;
    Locale id;
    Random random;
    String template, idberat, idharga;
    private Dialog dialog;
    LayoutInflater inflater;
    ImageView goku;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart);
        lanjutBelanja = findViewById(R.id.lanjutBelanjaChart);
        lanjutBelanja.setOnClickListener(v -> 
            Intent intent = new Intent(getApplicationContext(), List_Kado.class);
            startActivity(intent);
        );

        getHargaAwal = getIntent().getIntExtra("harga", 0);

        Log.d("setHarga", getHargaAwal + "");

        dialog  = new Dialog(CartActivity.this);
        inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.loading, null);
        goku = layout.findViewById(R.id.custom_loading_imageView);
        goku.animate().rotationBy(360).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCancelable(false);
        dialog.setContentView(layout);
        dialog.show();

        id = new Locale("id", "ID");

        format = NumberFormat.getCurrencyInstance(id);

        random = new Random();
        lastNumber = 0;

        for (int k = 0; k < 3; k++)
            lastNumber+=(random.nextInt(10)*Math.pow(10, k));
        

        backCart = findViewById(R.id.backCartNav);
        backCart.setOnClickListener(v -> finish());

        Checkout = findViewById(R.id.checkoutChart);
        totalbelanjar = findViewById(R.id.totalBelanjaChart);
        totalberat = findViewById(R.id.totalBeratChart);
        recyclerView = findViewById(R.id.rvChart);

        preferences = PreferenceManager.getDefaultSharedPreferences(CartActivity.this);
        uidku = preferences.getString("uid", "");
        madolCarts = new ArrayList<>();
        getCart();
        glm = new GridLayoutManager(CartActivity.this, 1);
        recyclerView.setLayoutManager(glm);

        Checkout.setOnClickListener(view -> 
            Intent intent = new Intent(CartActivity.this, CheckoutActivity.class);
            intent.putExtra("idharga", idharga);
            intent.putExtra("name", namacart);
            preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            editor = preferences.edit();
            editor.remove("range");
            editor.remove("acara");
            editor.remove("buat");
            editor.apply();
            startActivity(intent);

        );

        LocalBroadcastManager.getInstance(this).registerReceiver(passValue, new IntentFilter("message_subject_intent"));

        ItemTouchHelper.SimpleCallback callback = new RecyclerTouchDelete(0, ItemTouchHelper.LEFT, this);
        new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);
    

    public String LoadData(String inFile) 
        String tContents = "";

        try 
            InputStream stream = getAssets().open(inFile);

            int size = stream.available();
            byte[] buffer = new byte[size];
            stream.read(buffer);
            stream.close();
            tContents = new String(buffer);
         catch (IOException e) 
            // Handle exceptions here
        

        return tContents;

    

    private String replaceNumberOfAmount(String original, int replace)
        return original.substring(0, original.length() - 3) + replace;
    

//    private void senderEmail()
//        SenderAgent senderAgent = new SenderAgent("gify.firebase@gmail.com", "Confirmation Transaction Gify", templateConvert, CartActivity.this);
//        senderAgent.execute();
//    

    private void getCart()
        JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETCART, null, response -> 
            try 
                JSONArray array = response.getJSONArray("YukNgaji");
                for (int a = 0; a < array.length(); a++)
                    JSONObject object = array.getJSONObject(a);
                    String id_tetap = object.getString("id_tetap");
                    if (id_tetap.equalsIgnoreCase(uidku))
                        kuantitas = object.getInt("jumlah");
                        idbarang = object.getInt("id_barang");
                        idharga = object.getString("harga");
                        idberat = object.getString("berat");
                        getBerat(idbarang);
                        dialog.dismiss();
                    
                
                dialog.dismiss();

             catch (JSONException e) 
                e.printStackTrace();
            
        , error -> 
            Log.d("getcart", "getCart: " + error.getMessage());
        );
        RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
        queue.add(objectRequest);
    

    public BroadcastReceiver passValue = new BroadcastReceiver() 
        @Override
        public void onReceive(Context context, Intent intent) 
            namacart = intent.getStringExtra("name");
            Log.d("hargalast", namacart + "");
            namacart = intent.getStringExtra("title");
            template = "<h2> Gify Transaction </h2> " +
                    "<h3> Kamu baru saja melakukan pesanan dengan detail sebagai berikut </h3>"
                    + "<p><b> Nama barang: </p></b>"
                    + "<p><b> Harga barang" + format.format(Double.valueOf(replaceNumberOfAmount(idharga, lastNumber))) + ". Silahkan transfer dengan tiga digit terakhir yaitu :" + lastNumber + "</p></b>"
                    + "<p><b> Jika sudah melakukan pembayaran, silahkan konfirmasi disini </p></b>"
                    + "https://api.whatsapp.com/send?phone=082325328732&text=Confirmation%20Text"
                    + "<h2>Salam, Gify Team</h2>";
            Log.d("hargalast", idharga + lastNumber);
            templateConvert = Html.fromHtml(template);
        
    ;

    private void getBerat(int idbarang)
        JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG, null, response -> 
            try 
                JSONArray array = response.getJSONArray("YukNgaji");
                for (int a = 0; a < array.length(); a++)
                    JSONObject object = array.getJSONObject(a);
                    int id_barang = object.getInt("id");
                    if (idbarang==id_barang)
                        String gambar = object.getString("photo");
                        int harga = object.getInt("harga");
                        String namacart = object.getString("nama");
                        int berat = object.getInt("berat");
                        MadolCart madolCart = new MadolCart(gambar, harga, namacart, idbarang, kuantitas, berat);
                        madolCarts.add(madolCart);
                        adapterCart = new AdapterCart(madolCarts, CartActivity.this, totalbelanjar, totalberat);
                        recyclerView.setAdapter(adapterCart);
                    
                
             catch (JSONException e) 
                e.printStackTrace();
            
        , error -> 
            Log.d("jsoner", "getBerat: " + error.getMessage());
        );
        RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
        queue.add(objectRequest);
    

    @Override
    public void onSwipe(RecyclerView.ViewHolder viewHolder, int dir, int pos) 
        if (viewHolder instanceof AdapterCart.MyCart)
            String name = madolCarts.get(viewHolder.getAdapterPosition()).getNamacart();

            MadolCart madolCart = madolCarts.get(viewHolder.getAdapterPosition());
            int deleteIndex =  viewHolder.getAdapterPosition();

            Log.d("taptap", "onSwipe: " + madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());

            GETBARANG(madolCarts.get(viewHolder.getAdapterPosition()).getNamacart());

            adapterCart.removeItem(viewHolder.getAdapterPosition());
        
    

    private void deletecart(String id_barang)
        StringRequest stringRequest = new StringRequest(Request.Method.GET, DELETECART+"?idtetap="+uidku+"&idbarang="+id_barang, response -> 
            try 
                if (response.equalsIgnoreCase("bisa"))
                    Toast.makeText(CartActivity.this, "Barang telah di hapus", Toast.LENGTH_SHORT).show();
                    Log.d("bisabarangcart", "GETBARANG: " );
                
            catch (Exception e)
                Log.d("ekscartactivity", "deletecart: " + e.getMessage());
            
        , error -> 
            Log.d("ernocartdel", "deletecart: " + error.getMessage());
        );
        RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
        queue.add(stringRequest);
    

    private void GETBARANG(String namas)
        JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, GETBARANG,null, response -> 
            try 
                JSONArray array = response.getJSONArray("YukNgaji");
                for (int a = 0; a < array.length(); a++)
                    JSONObject object = array.getJSONObject(a);
                    String nama = object.getString("nama");
                    if (nama.equalsIgnoreCase(namas))
                        Log.d("namabarang", "GETBARANG: " + nama + " s " + namas);
                        String id = object.getString("id");
                        deletecart(id);
                    
                
            catch (Exception e)
                Log.d("barangexce", "GETBARANG: " + e.getMessage());
            
        , error -> 
            Log.d("errorgetbrng", "GETBARANG: " + error.getMessage());
        );
        RequestQueue queue = Volley.newRequestQueue(CartActivity.this);
        queue.add(objectRequest);
    


为了计算总价,我使用了这段代码

public int totalCart(ArrayList<MadolCart> items, String name)

    for(int i = 0 ; i < items.size(); i++) 
        totalname = items.get(i).getNamacart();
        if (totalname.equals(name))
            totalharga += items.get(i).getHarga();
        
    
    return totalharga;

我将求和代码放在一个方法中,如果单击按钮 + 则调用该方法

如果按钮 - 被点击它会调用这个方法

public int kurangtotalcart(ArrayList<MadolCart> items, String name)

    for(int i = 0 ; i < items.size(); i++) 
        totalname = items.get(i).getNamacart();
        if (totalname.equals(name))
            totalharga -= items.get(i).getHarga();
        
    
    return totalharga;

现在 idk 如何在回收站视图中为每个位置/项目获取单独的数量,然后将其发送到活动,格式为 (1, 2, 3) (,) 表示每个项目的分隔符 如何从回收站查看项目位置获取价值分离数量?

已解决

public String getSeperatedquantity(List<MadolCart> quantity)

    String kus = "";
    for (int i = 0; i < quantity.size(); i++)
        kus += quantity.get(i).getQuantity() + ", ";
    

    return kus;

【问题讨论】:

请不要因为使用 android-studio 标签而标记问题:Android Studio 标签应该在您对 IDE 本身有疑问时使用,而不是您在其中编写(或想要编写)的任何代码。请参阅 when is it appropriate to remove an IDE tag、How do I avoid misusing tags? 和 the tagging guide。请改用 [android] 或其他相关标签。 【参考方案1】:

我通过添加以下内容找到了解决方案:

public String getSeperatedquantity(List<MadolCart> quantity)

        String kus = "";
        for (int i = 0; i < quantity.size(); i++)
            kus += quantity.get(i).getQuantity() + ", ";
        

        return kus;
    

【讨论】:

以上是关于如何从购物车中的每件商品中获取数量并传递给活动?的主要内容,如果未能解决你的问题,请参考以下文章

如何将单个商品的数量和价格传递给 PayPal?

如何用JS算出商品总价!

限制 Woocommerce 中的购物车商品数量

如何在 Vue.js 中获取购物车商品的总价格并乘以数量

JAVA EE中如何使用session实现购物车的功能?

(十七)将商品添加到购物车