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 andAndroid 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
<
linearlayout
android:background
=
"#ffffff"
android:layout_height
=
"fill_parent"
android:layout_width
=
"fill_parent"
android:orientation
=
"vertical"
<
linearlayout
android:id
=
"@+id/LinearLayoutHeader"
android:layout_height
=
"wrap_content"
android:layout_width
=
"wrap_content"
android:orientation
=
"horizontal"
>
<
imageview
android:adjustviewbounds
=
"true"
android:id
=
"@+id/ImageViewProduct"
android:layout_height
=
"wrap_content"
android:layout_margin
=
"5dip"
android:layout_width
=
"wrap_content"
android:scaletype
=
"fitXY"
android:src
=
"@drawable/deadoralive"
></
imageview
>
<
textview
android:id
=
"@+id/TextViewProductTitle"
android:layout_gravity
=
"center"
android:layout_height
=
"wrap_content"
android:layout_margin
=
"5dip"
android:layout_width
=
"wrap_content"
android:text
=
"Dead or Alive"
android:textcolor
=
"#000000"
android:textsize
=
"26dip"
></
textview
>
</
linearlayout
>
<
textview
android:id
=
"@+id/TextViewProductPrice"
android:layout_height
=
"wrap_content"
android:layout_margin
=
"5dip"
android:layout_width
=
"fill_parent"
android:text
=
"Product Price"
android:textcolor
=
"#000000"
android:textstyle
=
"bold"
></
textview
>
<
textview
android:id
=
"@+id/TextViewProductDetails"
android:layout_height
=
"wrap_content"
android:layout_margin
=
"5dip"
android:layout_weight
=
"1"
android:layout_width
=
"fill_parent"
android:text
=
"Product description"
android:textcolor
=
"#000000"
></
textview
>
<
linearlayout
android:id
=
"@+id/linearLayoutCurrentlyInCart"
android:layout_height
=
"wrap_content"
android:layout_width
=
"fill_parent"
>
<
textview
android:id
=
"@+id/textViewCurrentlyInCart"
android:layout_height
=
"wrap_content"
android:layout_margin
=
"5dip"
android:layout_width
=
"wrap_content"
android:text
=
"Currently in Cart:"
android:textcolor
=
"#000000"
android:textsize
=
"20dip"
></
textview
>
</
linearlayout
>
<
linearlayout
android:id
=
"@+id/linearLayoutAddLayout"
android:layout_height
=
"wrap_content"
android:layout_margin
=
"5dip"
android:layout_width
=
"fill_parent"
android:orientation
=
"horizontal"
>
<
textview
android:id
=
"@+id/textView1"
android:layout_height
=
"wrap_content"
android:layout_width
=
"wrap_content"
android:text
=
"Quantity:"
android:textcolor
=
"#000000"
></
textview
>
<
edittext
android:gravity
=
"right"
android:id
=
"@+id/editTextQuantity"
android:inputtype
=
"number"
android:layout_height
=
"wrap_content"
android:layout_weight
=
"1"
android:layout_width
=
"wrap_content"
android:text
=
"1"
></
edittext
>
<
button
android:id
=
"@+id/ButtonAddToCart"
android:layout_gravity
=
"right"
android:layout_height
=
"wrap_content"
android:layout_width
=
"wrap_content"
android:text
=
"Set Quantity"
></
button
>
</
linearlayout
></
linearlayout
>
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
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.
沒有留言:
張貼留言