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.
hey guys.. really appreciate this =] ! been waiting for this part for a long time haha nice one ! thx =D
ReplyDeletewee thnkx..waiting so long for this part
ReplyDeleteHey 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.
ReplyDeleteI 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.
DeleteHey,
Deletedid 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
Also working on it, updates soon...
DeleteHi
DeleteIs there anything new.
Please help
anyone having solution foe this issue of displaying wrong product in productdetails activity while clicking in shopping cart??? plzzz help
DeleteHello... Can you give me all 3 of this tutorial on shopping cart??
ReplyDeleteI need it as revision..
Plizzz...
Thaks a lot again
ReplyDeleteThanks A lop....
ReplyDeleteHi, 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.
ReplyDeleteThanks.
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.
ReplyDeleteThanks. plzz plzz plzz
Thank you guys for such nice post..will u plz guide me where to add layout xml for the view ..in third tutorial
ReplyDeleteThank 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. (:
ReplyDeleteadd classes to manifest
DeleteI 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
DeleteSolution:
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!
Thanks a lot. I could solve my big issue.
ReplyDeleteThank 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..
ReplyDeleteDear Admin Sir,
ReplyDeleteIf 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...
@BusinessIsGood: You really helped me. Kindly help me in changing the INR, USD, EUR and get the updated price.
ReplyDelete"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..
ReplyDeleteMy email id is poongkundrans@gmail.com
Can you teach me how to complete the application after clicking on the "proceed to checkout" button. I really need your help.
ReplyDelete@ ShowTop
Deletedid u manage to complete the application by clicking the checkout button please post the instructions..i really need the final part
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
ReplyDeleteHi
DeleteI wonder if you did this
Please help me
Thabks
How do I include the "Process to checkout" Button to ShoppingCartActivity.java? Can anybody please help.
ReplyDeletewhere can i download the source code ?
ReplyDeleteNice tutorial, Thanks...
ReplyDeleteWhen we click an item from the shopping cart it opens wrong item from the catalog.
ReplyDeleteits ok son.dan palayan
Deleteyes sir y is that?
ReplyDeleteWhy I keep with error when create another new catalog?
ReplyDeleteIs there any method to add on another catalog?
anyone here know how to link the selected item item into sqlite?
ReplyDeleteHii..!!
ReplyDeleteThis is a wonderful example , please make the code downloadable ..
Thanks in advance..!!
Hi
ReplyDeletePlz help me to Change Shopping Cart Online.
Advance Thanks
Items is not showing in first page
ReplyDeleteNice Tutorial sir,
ReplyDeleteCan 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.
Nice tutorial sir.
ReplyDeleteThank You
how to add function delete data cart ?
ReplyDeletewhen i run the app on real device it installs successfully but unfortunately stops when i try to open
ReplyDeleteIts 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.
ReplyDeleteboss, are got the solution!!! please help me. my email id:vinodkumargulumuru@gmail.com
DeleteBy 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?
ReplyDeleteThank you so much for this tutorial. it has really helped me out.
ReplyDeleteThankyou 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
ReplyDeleteadd internet permission in your manifest.xml
Deletesir, how to implement same concept in recyclerview and cardview!!!
ReplyDeletePlease Forward me this entire Project,I am Doing project it will be very Helpful.Thanks In Advance.
ReplyDeletehi puneeth this is the url: https://github.com/dreamdom/Shopping-Cart-Tutorial-part-2
ReplyDeletehow can we get the data from mysql server using php. please any one help me.....
ReplyDeleteYes 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
ReplyDeleteCan someone assist me to post the final stage of this tutorial,it is very nice job.
ReplyDeleteHow to add items in cart in different catalog?
ReplyDelete