Saturday, June 9, 2012

Android Shopping Cart Tutorial Part 3

In this part of the Android Shopping Cart Tutorial we will add prices, and calculate the total price for the purchase.


This tutorial is part of a series about building an android based shopping cart, and will build off of existing code and concepts discussed in Android Shopping Cart Tutorial and Android Shopping Cart Tutorial Part 2.

Step 1. Prices for Products

In our previous tutorials we learned how to display different products, add them to the cart, and even change the quantity of those products. Now we must add another crucial component, the price.

If you look back at the previous tutorials, our Product object already contains price information, and our initial catalog is setting prices--these prices simply are not being displayed in the app anywhere.



Step 2. Modify the productdetails.xml Layout

In theory, we could append the price to the product description, but we may want it to stand out a little more. To help accomplish this, we will add a separate view to the layout to put the pricing information.

Listed below is the layout xml for the view we will add.

<TextView android:layout_height="wrap_content" android:id="@+id/TextViewProductPrice"
 android:layout_width="fill_parent" android:layout_margin="5dip"
 android:textColor="#000000" android:text="Product Price" android:textStyle="bold"></TextView>

Listed below is the complete source for the productdetails.xml file


 
  
  

 

 

 

 
  
 


 
  
  
  
 


The complete code for the ProductDetialsActivity.java is listed below:

package com.dreamdom.tutorials.shoppingcart;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ProductDetailsActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.productdetails);

  List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());

  int productIndex = getIntent().getExtras().getInt(
    ShoppingCartHelper.PRODUCT_INDEX);
  final Product selectedProduct = catalog.get(productIndex);

  // Set the proper image and text
  ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
  productImageView.setImageDrawable(selectedProduct.productImage);
  TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
  productTitleTextView.setText(selectedProduct.title);
  TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
  productDetailsTextView.setText(selectedProduct.description);
  
  TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
  productPriceTextView.setText("$" + selectedProduct.price);

  // Update the current quantity in the cart
  TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
  textViewCurrentQuantity.setText("Currently in Cart: "
    + ShoppingCartHelper.getProductQuantity(selectedProduct));

  // Save a reference to the quantity edit text
  final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);

  Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
  addToCartButton.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    // Check to see that a valid quantity was entered
    int quantity = 0;
    try {
     quantity = Integer.parseInt(editTextQuantity.getText()
       .toString());

     if (quantity < 0) {
      Toast.makeText(getBaseContext(),
        "Please enter a quantity of 0 or higher",
        Toast.LENGTH_SHORT).show();
      return;
     }

    } catch (Exception e) {
     Toast.makeText(getBaseContext(),
       "Please enter a numeric quantity",
       Toast.LENGTH_SHORT).show();

     return;
    }

    // If we make it here, a valid quantity was entered
    ShoppingCartHelper.setQuantity(selectedProduct, quantity);

    // Close the activity
    finish();
   }
  });

 }

}

Step 4. Add a "Total Price" Text View to shoppingcart.xml

Similar to how we modified the ProductDetails.xml layout to include a view for displaying the price, we want to modify the shoppingcart.xml layout to include a view to display the total price.

Listed below is the layout xml for the view we will add:

<TextView android:layout_height="wrap_content" android:id="@+id/TextViewSubtotal"
android:layout_width="fill_parent" android:layout_margin="5dip"
android:textColor="#000000" android:text="Subtotal" android:textStyle="bold"></TextView>

And listed below is the full code for shoppingcart.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_height="fill_parent"
 android:layout_width="fill_parent" android:background="#ffffff">

 <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:textColor="#000000"
  android:textSize="24dip" android:layout_margin="5dip" android:text="Shopping Cart"></TextView>
 <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dip" android:text="Click on a product to edit the quantity"></TextView>
  <TextView android:layout_height="wrap_content" android:id="@+id/TextViewSubtotal"
  android:layout_width="fill_parent" android:layout_margin="5dip"
  android:textColor="#000000" android:text="Subtotal" android:textStyle="bold"></TextView>
 <ListView android:layout_height="wrap_content"
  android:layout_weight="1" android:id="@+id/ListViewCatalog"
  android:layout_width="fill_parent" android:background="#ffffff"
  android:cacheColorHint="#ffffff" android:clickable="true"
  android:choiceMode="multipleChoice">

 </ListView>
 <LinearLayout android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:orientation="horizontal"
  android:layout_margin="5dip"
  android:id="@+id/LinearLayoutCheckout" android:layout_gravity="right">
  <Button android:id="@+id/Button02" android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:text="Proceed to Checkout"></Button>
 </LinearLayout>


</LinearLayout>

Step 5. Calculate and Display the Total Price in the ShoppingCartActivity file

Now, when the activity loads we will loop through all the items in the cart, add together the prices, and then display this sum as the Total Price.

We will do this in the onResume call, since it is possible to change product quantities in the shopping cart after this activity has been created.

Listed below is the code to add to calculate the subtotal:

double subTotal = 0;
for(Product p : mCartList) {
 int quantity = ShoppingCartHelper.getProductQuantity(p);
 subTotal += p.price * quantity;
}

TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);

And listed below is the full code for the ShoppingCartActivity file:

package com.dreamdom.tutorials.shoppingcart;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ShoppingCartActivity extends Activity {
 
 private List<Product> mCartList;
 private ProductAdapter mProductAdapter;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.shoppingcart);
  
  
  mCartList = ShoppingCartHelper.getCartList();
  
  // Make sure to clear the selections
  for(int i=0; i<mCartList.size(); i++) {
   mCartList.get(i).selected = false;
  }

  
  // Create the list
  final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
  mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true);
  listViewCatalog.setAdapter(mProductAdapter);
  
  listViewCatalog.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position,
     long id) {
    Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
    productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
    startActivity(productDetailsIntent);
   }
  });
  
 }
 
 @Override
 protected void onResume() {
  super.onResume();
  
  // Refresh the data
  if(mProductAdapter != null) {
   mProductAdapter.notifyDataSetChanged();
  }
  
  double subTotal = 0;
  for(Product p : mCartList) {
   int quantity = ShoppingCartHelper.getProductQuantity(p);
   subTotal += p.price * quantity;
  }
  
  TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
  productPriceTextView.setText("Subtotal: $" + subTotal);
 }

}

Screenshot of the App in Action

Listed below is a screenshot of the application in action.



Final Notes

It is actually not recommended to use decimals to calculate prices in Java applications. A better option would be to use the BigDecimal class.
------------------------------------------------------------

We create these tutorials in our free time. If you like what you see please consider buying us a cup of coffee so we can keep creating useful material. Click on the image below to make a donation via Paypal.

55 comments:

  1. hey guys.. really appreciate this =] ! been waiting for this part for a long time haha nice one ! thx =D

    ReplyDelete
  2. wee thnkx..waiting so long for this part

    ReplyDelete
  3. Hey i really liked the tutorial. Its so very perfect. But there is a flaw, Inside shopping cart if you press on a item it would be mapped to some other different item. I tried to correct it in the source code But was not successful. Please go through.

    ReplyDelete
    Replies
    1. I found the same mistake. Maybe it's because we take the position of a product in the list. If product no. 3 in the catalog is the first product in the shopping cart, and in the shopping cart you click on this product, the product details of the product no. 1 in the catalog opens. But I haven't found a solution yet.

      Delete
    2. Hey,
      did anyone of you find the solution? please help me.. I'm looking for that since long time and no solution!!
      please how to correct the problem?
      thank you in advance

      Delete
    3. Also working on it, updates soon...

      Delete
    4. Hi
      Is there anything new.
      Please help

      Delete
    5. anyone having solution foe this issue of displaying wrong product in productdetails activity while clicking in shopping cart??? plzzz help

      Delete
  4. Hello... Can you give me all 3 of this tutorial on shopping cart??
    I need it as revision..
    Plizzz...

    ReplyDelete
  5. Hi, please help me in generating a string from all the selected items, quantity and the total price on the OnClickListener on the checkOut button in the Shopping Cart Activity.
    Thanks.

    ReplyDelete
  6. please help me in generating a string from all the selected items, quantity and the total price on the OnClickListener on the checkOut button in the Shopping Cart Activity.
    Thanks. plzz plzz plzz

    ReplyDelete
  7. Thank you guys for such nice post..will u plz guide me where to add layout xml for the view ..in third tutorial

    ReplyDelete
  8. Thank you so much, this series of tutorials helped me a lot. After the second part of this tutorial everything was working ok, then I decided to implement this third part but unfortunately I'm really noob at developing Android Apps. At first it seemed like the productdetails.xml file had some syntax errors ( I just changed some lowercases and they disapeared ) The real problem was when I first started the application. The first activity (catalog) works but when I click on one item it suddently stops and android says unfortulately application has stopped. I also downloaded the source of second tutorial from github and updated the app with this tutorial but it seems like I'm missing something. Any suggestions are more than welcome. Sorry for the long post. (:

    ReplyDelete
    Replies
    1. I also encountered the same problem but after going through the code keenly I realized the problem was however the lower-casing used to define the attributes in productdetails.xml

      Solution:
      In your productdetails.xml of the 2nd-part of the tutorial, add this code immediately after the closing tag of the 2nd LinearLayout(i.e

      That solves the whole issue. Thank you!

      Delete
  9. Thanks a lot. I could solve my big issue.

    ReplyDelete
  10. Thank u ... U solved my problem which lasted for over a month... Can u please add Discounted price field and mail to rchethankumar@hotmail.com at the earliest.... Thanks in advance..

    ReplyDelete
  11. Dear Admin Sir,
    If we want to change the INR, EUR and get the updated price for billing according to their country money value what to add. I request you to kindly please say.

    If anyone can help me also genius are welcome...

    ReplyDelete
  12. @BusinessIsGood: You really helped me. Kindly help me in changing the INR, USD, EUR and get the updated price.

    ReplyDelete
  13. "PAY PAL" Transaction link how to include. Then what and all functionality we want to ADD. Please say this also BOSS. Genius Help me please..
    My email id is poongkundrans@gmail.com

    ReplyDelete
  14. Can you teach me how to complete the application after clicking on the "proceed to checkout" button. I really need your help.

    ReplyDelete
    Replies
    1. @ ShowTop
      did u manage to complete the application by clicking the checkout button please post the instructions..i really need the final part

      Delete
  15. hii, can you please explain how to add values from multiple intents in same cart.Suppose i have 1 list of books as above and another list of some other item.I want that both selected books and other items should appear in same cart on doing add to cart button.Can you suggest how to do it ites urgent

    ReplyDelete
    Replies
    1. Hi
      I wonder if you did this
      Please help me
      Thabks

      Delete
  16. How do I include the "Process to checkout" Button to ShoppingCartActivity.java? Can anybody please help.

    ReplyDelete
  17. where can i download the source code ?

    ReplyDelete
  18. When we click an item from the shopping cart it opens wrong item from the catalog.

    ReplyDelete
  19. Why I keep with error when create another new catalog?
    Is there any method to add on another catalog?

    ReplyDelete
  20. anyone here know how to link the selected item item into sqlite?

    ReplyDelete
  21. Hii..!!
    This is a wonderful example , please make the code downloadable ..
    Thanks in advance..!!

    ReplyDelete
  22. Hi
    Plz help me to Change Shopping Cart Online.
    Advance Thanks

    ReplyDelete
  23. Items is not showing in first page

    ReplyDelete
  24. Nice Tutorial sir,

    Can you tell me, how to get data from listview shoping_cart.xml with click button then showing data listview in alert dialog ?

    please help me sir,
    Thank You.

    ReplyDelete
  25. how to add function delete data cart ?

    ReplyDelete
  26. when i run the app on real device it installs successfully but unfortunately stops when i try to open

    ReplyDelete
  27. Its really a nice and real time tutorial. thanks for the post. I have tried to get strings from ListView in ShoppingCartActivity to DB using JSON. but little hard to get it. Any help?!? will be great.

    ReplyDelete
    Replies
    1. boss, are got the solution!!! please help me. my email id:vinodkumargulumuru@gmail.com

      Delete
  28. By the way can i sort the catalog into 8 different categories of product, where i have each button representing 1 category as i click? How should i modify the code?

    ReplyDelete
  29. Thank you so much for this tutorial. it has really helped me out.

    ReplyDelete
  30. Thankyou for this tutorial. my project isn't working tho. When i press run it says unfortunately basket has stopped, could you send me the manifest,? thanks

    ReplyDelete
    Replies
    1. add internet permission in your manifest.xml

      Delete
  31. sir, how to implement same concept in recyclerview and cardview!!!

    ReplyDelete
  32. Please Forward me this entire Project,I am Doing project it will be very Helpful.Thanks In Advance.

    ReplyDelete
  33. hi puneeth this is the url: https://github.com/dreamdom/Shopping-Cart-Tutorial-part-2

    ReplyDelete
  34. how can we get the data from mysql server using php. please any one help me.....

    ReplyDelete
  35. Yes your absolutely right you can make a slide appear in JavaScript and presumably make a couple of other phenomenal things however your constrained by two components How long it takes you and to what extent it takes the end clients gadget (if its a cell phone or desktop). java

    ReplyDelete
  36. Can someone assist me to post the final stage of this tutorial,it is very nice job.

    ReplyDelete
  37. How to add items in cart in different catalog?

    ReplyDelete