Creating Shopping cart in android : Step by Step tutorial - SpartaCode

SpartaCode

Make your development faster and easier !

Creating Shopping cart in android : Step by Step tutorial





Shopping Cart is most important feature of all Ecommerce Apps.
If you want to create cart system as quickly as possible this is right place. Its basic yet customizable Shopping Cart for Android.

Here,
I introduce you with simplest and Customisable Shopping Cart System.

Following is Step By Step Details of implementation :

Step 1 : Create new Activity and Copy this into Layout file : activity_cart.xml

<RelativeLayout android:background="#e1e1e1"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:id="@+id/layout_total"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:padding="5dp"
        android:weightSum="2">
        <TextView android:gravity="end"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:text="Total : "
            android:textSize="20dp">
        </TextView>

        <TextView
            android:id="@+id/tv_total"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:text="0 Rs"
            android:textSize="20dp">
        </TextView>
    </LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_cart"
        android:layout_above="@+id/btn_placeorder"
        android:layout_below="@+id/layout_total"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </android.support.v7.widget.RecyclerView>


    <Button
        android:id="@+id/btn_placeorder"
        android:layout_gravity="center"
        android:layout_alignParentBottom="true"
        android:layout_height="60dp"
        android:layout_width="match_parent"
        android:onClick="insertOrder"
        android:text="Place Order"
        android:textColor="@android:color/white"
        android:theme="@style/Theme.MaterialButton">
    </Button>

</RelativeLayout>


Copy single ItemLayout XML file: 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_myevent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardElevation="5dp"
        card_view:cardUseCompatPadding="true"
        android:clickable="true"
        android:foreground="?attr/selectableItemBackground"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:weightSum="4"
            >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="10dp"
                >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:weightSum="5"
                    android:gravity="center"
                    >

                    <TextView
                        android:id="@+id/tv_name"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="Itemname"
                        android:layout_weight="0.75"
                        android:textSize="13dp"
                        />

                    <TextView
                        android:id="@+id/tv_size"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="Size"
                        android:textSize="13dp"
                        android:textAlignment="center"
                        android:layout_weight="1.1"

                        />

                    <TextView
                        android:id="@+id/tv_rate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="Rate"
                        android:textAlignment="center"
                        android:layout_weight="1"
                        android:textSize="13dp"
                        />

                    <TextView
                        android:id="@+id/tv_total"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="?android:attr/textAppearanceMedium"
                        android:text="Total"
                        android:layout_toRightOf="@+id/tv_qty"
                        android:textAlignment="center"
                        android:textSize="13dp"
                        android:layout_weight="1"
                        />

                    <CheckBox
                        android:id="@+id/chk_selectitem"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1.15"
                        android:clickable="false"
                        />
                </LinearLayout>

            </LinearLayout>

        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Copy button style into style.xml in res->val->style.xml

    <style name="Theme.MaterialButton" parent="AppTheme">
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorButtonNormal">@color/colorPrimaryDark</item>
        <item name="colorControlHighlight">@color/colorAccent</item>
    </style>

Download Images and Put it into your Drawable package :






Step 2 : Copy this into corresponding Java Activity File:



public class CartActivity extends AppCompatActivity {

    RecyclerView recycler_itemlist;
    public static TextView tv_total;
    CartListAdapter cartListAdapter;
    public static int total=0;
    String jsonCartList;

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

        //Set back button to activity
        android.support.v7.app.ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setTitle("Cart");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        tv_total =(TextView) findViewById(R.id.tv_total);

        recycler_itemlist =(RecyclerView) findViewById(R.id.recycler_cart);
        recycler_itemlist.setHasFixedSize(true);
        recycler_itemlist.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        recycler_itemlist.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        recycler_itemlist.getRecycledViewPool().setMaxRecycledViews(0, 0);

        cartListAdapter = new CartListAdapter(CartActivity.this,ItemListAdapter.selecteditems);
        recycler_itemlist.setAdapter(cartListAdapter);

        getIntentData();

        calculateTotal();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; goto parent activity.
                this.finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void getIntentData(){
        if(getIntent()!=null && getIntent().getExtras()!=null){
           // Get the Required Parameters for sending Order to server.
        }
    }

    public static void calculateTotal(){
        int i=0;
        total=0;
        while(i<ItemListAdapter.selecteditems.size()){
            total=total + ( Integer.valueOf(ItemListAdapter.selecteditems.get(i).getRate()) * Integer.valueOf(ItemListAdapter.selecteditems.get(i).getQuantity()) );
            i++;
        }
        tv_total.setText(""+total);
    }

    public void insertOrder(View view){

            if(total>0){

            Gson gson = new Gson();
            jsonCartList = gson.toJson(ItemListAdapter.selecteditems);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                        case DialogInterface.BUTTON_POSITIVE:
                            //Yes button clicked
                            placeOrderRequest();
                            break;

                        case DialogInterface.BUTTON_NEGATIVE:
                            //No button clicked
                            break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
            builder.setMessage("Do you want to place Order ?").setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

        }else{
                Toast.makeText(CartActivity.this,"No items in Cart !",Toast.LENGTH_LONG).show();
            }


    }


    private void placeOrderRequest(){
       //Send Request to Server with required Parameters
    /*
   jsonCartList - Consists of Objects of all product selected.
    */
    
    }

}


Include gson and retrofit api :

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'





Step 3 : Copy model class required to capture all attributes of an Item/Product :




public class Item {

    public String ItemId;
    public String ItemName;
    public String Size;
    public String Company;
    public String Rate;

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

    public String Status;

    public String getQuantity() {
        return Quantity;
    }

    public void setQuantity(String quantity) {
        Quantity = quantity;
    }

    public String Quantity;

    public void setItemId(String ItemId){
        this.ItemId=ItemId;
    }
    public String getItemId(){
        return ItemId;
    }
    public void setItemName(String ItemName){
        this.ItemName=ItemName;
    }
    public String getItemName(){
        return ItemName;
    }
    public void setSize(String Size){
        this.Size=Size;
    }
    public String getSize(){
        return Size;
    }
    public void setCompany(String Company){
        this.Company=Company;
    }
    public String getCompany(){
        return Company;
    }
    public void setRate(String Rate){
        this.Rate=Rate;
    }
    public String getRate(){
        return Rate;
    }

    public String getJsonObject(){
        return "{ItemId:"+ItemId+",ItemName:"+ItemName+",Size:"+Size+",Company:"+Company+",Rate:"+Rate+"}";
    }
}




To create your custom Model class you can prefer my Automation Site :

Model Class Generator



Step 4 : Copy the CardListAdapter:

 
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import admin.employee.R;
import admin.employee.listeners.DeleteItemListener;
import admin.employee.listeners.QuantityListener;
import admin.employee.services.models.Item;


public class CartListAdapter extends RecyclerView.Adapter {
    private List callListResponses = new ArrayList<>();
    final List templist=new ArrayList<>();
    private Activity context;
    int lastPosition=0;

    public CartListAdapter(Activity context, List callListResponses)
    {
        super();
        this.context = context;
        this.callListResponses=callListResponses;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false);

        return new ViewHolder(itemView);
    }


    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final Item call = callListResponses.get(position);

        holder.itemname.setText(call.getItemName());
        holder.itemprice.setText(call.getRate()+" Rs");
        holder.itemsize.setText(call.getSize());
        holder.tv_quantity.setText(call.getQuantity());

        holder.cart_minus_img.setOnClickListener(new QuantityListener(context, holder.tv_quantity,call,false));
        holder.cart_plus_img.setOnClickListener(new QuantityListener(context, holder.tv_quantity,call,true));
        holder.img_deleteitem.setOnClickListener(new DeleteItemListener(context,call,this));
    }

    //Animating single element
    private void setAnimation(View viewToAnimate, int position)
    {
        if (position > lastPosition) {
            Animation animation = AnimationUtils.loadAnimation(context, R.anim.push_right_in);
            viewToAnimate.startAnimation(animation);
            lastPosition=position;
        }
        position++;
    }

    @Override
    public int getItemCount() {
        //Log.d("Size List:",String.valueOf(callListResponses.size()));
        if(callListResponses!=null){
            return callListResponses.size();
        }
        return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView itemprice,itemname, itemsize,tv_quantity;
        ImageView cart_minus_img, cart_plus_img,img_deleteitem;


        public ViewHolder(View itemView) {
            super(itemView);
            cart_minus_img=(ImageView) itemView.findViewById(R.id.cart_minus_img);
            cart_plus_img=(ImageView) itemView.findViewById(R.id.cart_plus_img);
            img_deleteitem=(ImageView) itemView.findViewById(R.id.img_deleteitem);
            itemname=(TextView) itemView.findViewById(R.id.itemname);
            itemprice=(TextView) itemView.findViewById(R.id.itemprice);
            itemsize=(TextView) itemView.findViewById(R.id.itemsize);
            tv_quantity=(TextView) itemView.findViewById(R.id.tv_quantity);

        }
    }



}



Step 5 : Copy the Sole of Cart, Adding Items:


We need to copy this static List variable into List Adapter used to display our Item / Product

Just copy this line into Recycler or List Adapter so that 
Items can be added into this list and it can be accessed from any where.

 

public static List <item> selecteditems;



You can check if list already contains item to be added like this :


        if(ItemListAdapter.selecteditems.contains(itemobject)){
           //List already contains item
        }else{
            //List does not contains item you can add item here.
            ItemListAdapter.selecteditems.add(itemobject);
        }




Step 6 : Removing Items from Cart :



            ItemListAdapter.selecteditems.remove(item);
            cartListAdapter.notifyDataSetChanged();
            CartActivity.calculateTotal();



Thank You for your Visit
If you like post, Please Share and Comment.

70 comments:

  1. Simple and customizable Cart is really awesome for beginners.

    ReplyDelete
  2. please provide such demo example to download.

    ReplyDelete
    Replies
    1. Hello Ankesh,
      Thank you for your message.. I will provide a demo project on this topic.

      Delete
    2. Hi can you please share the source code thanks
      frankboateng1992@hgmail.com is my account
      Thank you

      Delete
    3. can u share full code dharunramasundaram19@gmail.com please

      Delete
  3. Replies
    1. Hello Ankesh Which part is missing ?

      Delete
    2. what about adding amount ? user selects 2 of a product

      Delete
    3. When user selects two of product the amount is automatically multiplied by two and updated in total cost.

      Delete
  4. Thankyu for your sharing Sir.

    if you can, please give your code (demo) to github.
    or artdyora@gmail.com

    thankyu sir..

    ReplyDelete
  5. Hello Angkit, any class are missing that CartListAdapter. please how to create or get that class?

    ReplyDelete
    Replies
    1. Dear Art Dyora,
      Thank you for your Message.
      I will add complete source code for this topic.
      Please let me know which classes are missing.
      Its grateful to help you.

      Delete
    2. if you can, please give your code (demo) to github.
      or sureshprismsoft@gmail.com

      Delete
  6. Hi Ankit, Can you please provide a source code to download.

    ReplyDelete
    Replies
    1. please give full source code of this project please its humble request.
      Thanks & Regards
      yadavvipin798@gmail.com

      Delete
  7. if you can, please give your code (demo) to github.
    or sureshprismsoft@gmail.com

    ReplyDelete
  8. Nice tutorial.

    What about the xml design for the single item view

    ReplyDelete
    Replies
    1. I have added the XML design for single item view check it out.

      Delete
  9. ItemClickListener i cant import what can i do and push_right_in please tell me

    ReplyDelete
  10. Marketplaces are beneficial for both the online retailers as well as the customers. Entrepreneurs can start their business with zero inventories and also earn commission from the listed vendors.  ecommerce platform

    ReplyDelete
  11. if you can, please give your code (demo) to github.
    ashvinivhiremat@gmail.com

    ReplyDelete
  12. This seems incomplete. as indicated above there is no xml file for single item view. There is nothing regarding the necessary changes required to the Gradle (module). For a step-by-step guide it does not work in that for a new user it would be very difficult to follow - for example no indication of how to set up a java file. It really requires much more detailed explanation

    If these points were remedied it would be a good tutorial. If anyone has overcome these shortcomings I would love to hear from you

    ReplyDelete
    Replies
    1. Philip Swan sorry for inconsistancy.
      I have provided the single view of row please check it out.

      Delete
  13. Dear sir,

    please give full source code of this project please its humble request.
    Thanks & Regards
    abhishekkaushal36@gmail.com

    ReplyDelete
  14. Hello Sir,
    Please share full code of this project on naveen000028@gmail.com
    Thank you

    ReplyDelete
  15. Hello,
    Please share full code of this project on ipostam@hotmail.com
    Thank you

    ReplyDelete
  16. Hello,
    Please share full code of this project on
    nashishyadav.n20@gmail.com
    Thank you

    ReplyDelete
  17. where is row_single_item.xml file???

    ReplyDelete
  18. Hi, Please give your code to emprotekcorp@gmail.com

    thank you.

    ReplyDelete
  19. This class is not full, ItemClickListener.java and Retailer.java not displayed in this tutorial

    ReplyDelete
    Replies
    1. ItemClickListener is just onClickListener and Retailer.java is model class that is non of your business.

      Delete
  20. can you send souce code in ricots47@gmail.com
    thank you

    ReplyDelete
  21. Hi Ankit, it seems there in no complete code can u please mail me the complete code to nilesh.pal0497@gmail.com, Thank you.

    ReplyDelete
    Replies
    1. Hi Ankit, can you please mail me the source code to kratika.kukreja2009@gmail.com

      Delete
  22. can you send souce code in banklhon1995@gmail.com Thank you.

    ReplyDelete
  23. Can you send souce code in burak.keysoft@gmail.com Thank you

    ReplyDelete
  24. Hi Ankit, it seems there in no complete code can u please mail me the complete code to vedasaib@gmail.com, Thank you

    ReplyDelete
  25. Hi Ankit, please send me the full source code thank you.
    neehau.720@gmail.com

    ReplyDelete
  26. Hi Ankit, please send me full source code in dhanashrihemane123@gmail.com, thank you!!!!

    ReplyDelete
  27. Hi Ankit, please send me full source code to anjalidesireddy@gmail.com, thank you.

    ReplyDelete
  28. Hi Aniket,Please share the full source code@
    dapp6269@gmail.com
    Thanks..

    ReplyDelete
  29. so getjsonobject on item class, to made item that user needed go to server am i right?

    ReplyDelete
  30. Hi ankit please sent full source code to murujai1992@gmail.com

    ReplyDelete
  31. Hi Ankit, can you please mail me the full source code at kratika.kukreja2009@gmail.com. Thanks in advance.

    ReplyDelete
  32. hey Ankit, can you please mail it to me.(urgency-> College project)
    email id: pheonixfaisal@gmail.com

    thanks mate!

    ReplyDelete
  33. can you share your code on narendrasuthar2597@gmail.com

    ReplyDelete
  34. not complete demo,incomplete code so many things missing

    ReplyDelete
  35. hey Ankit
    i like the
    simple n compact
    can you please mail me the source code
    something sources are missing
    mail:write2rosbin@gmail.com

    ReplyDelete
  36. hi, nice work please send me source code mobilentegre@gmail.com

    ReplyDelete
  37. please send code to sandhiyamoorthy1995@gmail.com

    ReplyDelete
  38. please send the source code to raginisinha1996@gmail.com

    ReplyDelete
  39. please send the source code to sidpug@gmail.com

    ReplyDelete
  40. please send the code to drupad.h.sachania@gmail.com. thank you

    ReplyDelete
  41. Hi can you please share the demo code to bharath@techinflo.com it will be a great help for me. Thank you in andvance.

    ReplyDelete
  42. please send the code to 12mscit037@gmail.com thank you

    ReplyDelete
  43. Can you pls send the source code to the emulatorvcnr@gmail.com

    ReplyDelete
  44. Can you pls send the source code to the pavanitla@gmail.com

    ReplyDelete
  45. Hello Ankit.... Can you please send this to me on my email?
    prutha.trivedi.14@gmail.com

    ReplyDelete
  46. hello great tutorial but i am stuck with editing quantity in CartActivity will you please help me?

    ReplyDelete
  47. Hello Ankit.... Can you please send this to me on my email?
    alokk3436@gmail.com

    ReplyDelete
  48. hi. PLease share code to walkerpassions@gmail.com

    ReplyDelete
  49. Dear sir,

    please give full source code of this project please its humble request.
    Thanks & Regards
    saurabhbhola80@gmail.com

    ReplyDelete
  50. Incredible articles and awesome design. Your blog entry merits the greater part of the positive input it"s been getting. 이벤트속옷

    ReplyDelete