Shopping cart in android

Shopping cart in android

In this tutorial you will learn how to create a simple app that features several products which can be placed in a shopping cart. You can then view the contents of the shopping cart and remove items that you no longer want.


Update — after following this tutorial, be sure to check out part 2 and also check out part 3.


Creating a Shopping Cart for Android

A common problem that arises when developing Android applications is figuring out how to pass information from Activity to Activity within the Android application. This problem can be solved in two ways. For passing small amounts of information, you can put extras in the Intent that gets passed along to create the activity. For managing a larger, more complex amount of information the use of static variables is recommended.

Through this tutorial we will create a simple shopping cart. At the end of the tutorial, there are several suggestions for improving the shopping cart. Some of these suggestions may be included in a future tutorial.

Screenshot of the finished Shopping Cart

Listed in the graphic below is an outline of how the activities and layouts are connected together. This tutorial will feature three different activities and several different layouts. The layout files are the xml files listed in blue.

The product adapter class is used in both the CatalogActivity and the ShoppingCartActivity to adapt data for the list views.

Activites and Layouts of the Shopping Cart

This shopping cart tutorial will involve several different layouts.

  • Catalog
  • Product Details
  • Shopping Cart

When the app starts, you will be immediately presented with the Catalog layout. From the catalog layout you can click on a product to view more details about it, and from there, you can add the product to your cart.

After adding the product to your cart, you will be taken back to the Catalog, where you can view details for other products or proceed to view your shopping cart.

The Shopping Cart layout will include the option to remove items from your cart, and to «Proceed to Checkout.»

Since this is an advanced tutorial, we will not focus on the details of creating these layouts. A more detailed tutorial on creating layouts can be found here.

Everything in this app revolves around the product class. The product class does not contain any of its own methods and really is just more of a container for other objects that describe the product including a title, an image, and a description.

The ShoppingCartHelper class is designed to hold information about all the products in the catalog, and all the products that are in the user’s shopping cart.

In this tutorial, our catalog is hard coded in, so the list of products, images, and descriptions will always be the same. This could be fine for your app if you sell a very limited number of items, don’t run into inventory issues and don’t need to frequently update your catalog.

In this example, lets say that we are selling books. I took some pictures of a couple books laying around that we can use in this tutorial.

Читайте также:  Где взять части андроида
Switch by Chip Heath and Dan Heath

Dead or Alive by Tom Clancy with Grant Blackwood
Watchmen by Alan Moore and Dave Gibbons

Make sure to download these images, and place them in your drawable folder. Make sure not to name the image of the book «switch» «switch.png» This is because the name is used in the generated class R, and switch is a java keyword.

For a more advanced shopping cart, you may wish to download an xml file containing catalog information, and parse out the xml information to dynamically update the catalog when the user runs the application.

By using static variables and static methods in the ShoppingCartHelper Class we allow any activity to access this catalog and shopping cart data, allowing us to easily and seamlessly access the same data in different activities in out application.

The Item layout represents how one product will be displayed in a list view in both the Catalog and Shopping Cart activities. It will show a thumbnail of the product, a title for the product, and optionally a checkbox.

Step 5. Create the ProductAdapter class

The ProductAdapter class is designed to be attached to a listview, and populate the data for the different products that will be in a list view. It uses the Item layout to populate the data in the list view.

The constructor for the ProductAdapter class also takes a boolean to determine if you want the checkbox to appear in the list or not. We only want the checkbox to appear in the Shopping Cart activity, so you can select multiple items in your cart and remove them if you wish.

Creating Adapters and using ListViews can be somewhat confusing, and I am definitely planning on doing a full detailed tutorial on that in the future.

In this step we will look at several snippets of code individually. Don’t worry about where to add them to your project—the complete CatalogActivity.java file is listed at the end of the step.

The Catalog Activity will display all the available products from the catalog. The Catalog Activity uses the ShoppingCartHelper to accomplish this.

This snippet demonstrates how to get a reference to the catalog of items.

When you click on an item in the catalog activity, we want it to take you to the ProductDetails Activity.

The ProductDetails Activity will be designed to be a generalized activity that can display information about any product. Since it is designed in this manner, it needs a way to figure out what product it should display details about. This is accomplished by passing along extras with the Intent that starts the activity.

Use Intent.putExtra to pass simple information between activities. In this case we will pass the index of the selected product.

Listed below is the full source for the Catalog Activity.

In the product details activity we will get the intent that started the activity, and extra the «extra» information that was passed along with the Intent to determine what product to display details about.

Читайте также:  Как форд фокус 3 подключить андроид

This is how to extract the extra information out of the Intent.

For the sake of keeping this tutorial more straightforward and not 100 pages long we are not doing error checking in this step. In reality, a well designed program should handle cases where getExtras returns null, or when trying to get a specifically named extra returns null. In these situations a well designed app should fail gracefully. It is not always safe to assume that the Intent extras will be present.

The full source for the ProductDetails Activity is listed below.

Screenshot of what the product details activity looks like in the final product.

Step 8. Finally, create the ShoppingCart Activity

Some code snippets are highlighted below. The full source for the ShoppingCartActivity.java is listed at the end of the step.

The shopping cart activity will display all the items in the user’s shopping cart. It will also display checkboxes next to the items, allowing the user to select multiple items at once and remove the items from the shopping cart if they so desire.

Just like the other activities, the ShoppingCartActivity uses the ShoppingCartHelper class to update the shopping cart

The product flag includes a «selected» boolean that we use to determine whether a checkbox should be selected in the shopping cart or not.

The code snippet below will run when the shopping cart activity first starts, and is designed to make sure none of the items are checked.

When the «Remove from Cart» button is pressed, all the checked items will be removed from the cart.

Our layout also includes a «Proceed to Checkout» button that could have functionality added to interact with an API to process credit card transactions.

The full code for the ShoppingCartActivity is listed below.

Try Out the App

Remember to update the application manifest before running the app.

Once you get the app working, try going between the activities and adding items to the shopping cart, and removing them. If you have any questions or problems feel free to ask in the comments section of this post.

Another screenshot of the finished app

Some Things to Think About

This tutorial represents an introduction to creating a shopping cart for Android. There are a number of ways that this application could be improved

  • Include options to display user reviews
  • Include option to handle quantities other than one
  • Add more items to the catalog
  • Dynamically download catalog information
  • Persist shopping cart data

Some more information on that last point. In this tutorial the ShoppingCartHelper will dynamically recreate the catalog if it is null, and dynamically recreate the ShoppingCart if it is null. However, if a user adds items to the shopping cart, exits the program, or the program is killed by the Android OS, when the program starts again the cart will be empty. It is generally a good practice to try to save user information, such as items in the shopping cart, since the Android OS has the ability to kill processes in order to free up memory for other processes.

Читайте также:  Как повысить мощность андроида

Remember, when you are designing a program that there are often many different ways to approach and solve the problem. There isn’t always a right answer, but some approaches may be faster or more flexible. This tutorial probably doesn’t include everything you want or need in a shopping cart, but use it as a starting point for creating one suited to your needs.

This tutorial was originally requested by a blog reader. If you questions of your own, or a request for a tutorial, don’t hesitate to comment and ask!

Update — after following this tutorial, be sure to check out part 2.

Источник

Shopping cart in android

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.

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

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

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:

And listed below is the full code for shoppingcart.xml

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:

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

Screenshot of the App in Action

Listed below is a screenshot of the application in action.

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

Источник

Оцените статью