day 24
购物车的实现
首先是在商品详情页点击加入购物车后,把该物品的数据存贮到一个集合中。
这里需要设计一个类实现数据的添加,删除和修改。
定义物品数据类
package Home.Data; import java.io.Serializable; public class Wares implements Serializable { private Long id; private String name; private String imgUrl; private String description; private int price; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
定义购物车数据类继承物品数据 添加数量属性
package Home.Data; import java.io.Serializable; public class ShoppingCart extends Wares implements Serializable { private int count; private boolean isChecked=true; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public boolean isChecked() { return isChecked; } public void setIsChecked(boolean isChecked) { this.isChecked = isChecked; } }
定义数据存储类包含一些添加删除的方法
package Home.utils; import android.content.Context; import android.util.SparseArray; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import Home.Data.ShoppingCart; public class CartProvider { public static final String CART_JSON="cart_json"; private SparseArray<ShoppingCart> datas =null; private Context mContext; public CartProvider(Context context){ mContext = context; datas = new SparseArray<>(200); listToSparse(); } public void put(ShoppingCart cart){ ShoppingCart temp = datas.get(cart.getId().intValue()); if (temp != null) { temp.setCount(temp.getCount() + 1); } else { temp = cart; temp.setCount(1); } datas.put(cart.getId().intValue(), temp); commit(); } public void update(ShoppingCart cart){ datas.put(cart.getId().intValue(),cart); commit(); } public void delete(ShoppingCart cart){ datas.delete(cart.getId().intValue()); commit(); } public List<ShoppingCart> getAll(){ return getDataFromLocal(); } public void commit(){ List<ShoppingCart> carts = sparseToList(); PreferencesUtils.putString(mContext,CART_JSON,JSONUtil.toJSON(carts)); } private List<ShoppingCart> sparseToList(){ int size = datas.size(); List<ShoppingCart> list = new ArrayList<>(size); for (int i=0;i<size;i++){ list.add(datas.valueAt(i)); } return list; } private void listToSparse(){ List<ShoppingCart> carts = getDataFromLocal(); if(carts!=null && carts.size()>0){ for (ShoppingCart cart: carts) { datas.put(cart.getId().intValue(),cart); } } } public List<ShoppingCart> getDataFromLocal(){ String json = PreferencesUtils.getString(mContext,CART_JSON); List<ShoppingCart> carts =null; if(json !=null ){ carts = JSONUtil.fromJson(json,new TypeToken<List<ShoppingCart>>(){}.getType()); } return carts; } }