您的位置:首页 > 其它

Cart 关于购物车里面需要封装的方法

2016-05-23 00:51 288 查看
对购物车进行增删改之后,都需要保存数据 saveCart();

//购物车需要当作对象 传递,要实现序列化接口Serializable
public class Cart implements Serializable {
//购物车里面的购物项集合
private List<CartItem> items = new ArrayList<CartItem>();

public List<CartItem> getItems() {
return this.items;
}

/**
* 修改图书的数量
*
* @param num
*/
public void modifyNum(int id, int num) {
Log.i("info","隐形了modifyNum方法:["+id+","+num+"]");
for (CartItem item : items) {
if (item.getBook().getId()==id) {
item.setCount(num);
saveCart();
return;
}
}
}

/**
* 移除购物项
*
*/
public void deleteBook(int id) {
for (CartItem item : items) {
if (item.getBook().getId()==id) {
items.remove(item);
return;
}
}
saveCart();
}

/**
* 购买
*
* @param book
*/
public boolean buy(Book book) {
for (int i = 0; i < items.size(); i++) {
CartItem item = items.get(i);
if (item.getBook().equals(book)) {
item.setCount(item.getCount() + 1);
return false;
}
}
//没有添加过
CartItem item = new CartItem(book, 1);
items.add(item);
saveCart();
return true;
}
//GlobalConsts.CART_CACHE_FILE_NAME);
//public static final String CART_CACHE_FILE_NAME="CART.INFO";
/**
* 持久化到文件中 下次打开应用购物车依然存在
*/
public void saveCart() {
try {
File file = new File(MyApplication.getContext().getCacheDir(), GlobalConsts.CART_CACHE_FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(this);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 从序列化的文件中读取购物车信息
*
* @return
*/
public Cart readCart() {
try {
File file = new File(MyApplication.getContext().getCacheDir(), GlobalConsts.CART_CACHE_FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Cart cart = (Cart) ois.readObject();
if(cart == null){
return new Cart();
}
return cart;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new Cart();
}

@Override
public String toString() {
return "Cart{" +
"items=" + items +
'}';
}

/**
* 1,1;2,3;4,1
*/
public String CartToString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
CartItem c = items.get(i);
sb.append(c.getBook().getId());
sb.append(","+c.getCount()+";");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
//获得购物车所有购物项的总价
public double getTotalPrice() {
double price = 0;
for(CartItem item:items){
price += item.getBook().getDangPrice()*item.getCount();
}
return price;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: