有greendao
另一个graadle
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
apply plugin: 'org.greenrobot.greendao'
greendao {
schemaVersion 1 //版本
daoPackage 'com.bw.arp.moni_demo.greendemo' // 一般为app包名+生成文件的文件夹名
targetGenDir 'src/main/java' //生成文件路径
}
//ButterKnife-依赖:
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
//Retrofit+Rxjava依赖:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'io.reactivex:rxandroid:1.2.0'
//Glide
compile 'com.github.bumptech.glide:glide:3.6.1'
//fresco依赖:
compile 'com.facebook.fresco:fresco:+'
//fresco加载gif依赖:
compile 'com.facebook.fresco:animated-gif:+'
//拦截器
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'org.greenrobot:greendao:3.1.0'
compile 'com.fynn.fluidlayout:fluidlayout:1.0'
//刷新控件springview
compile 'com.liaoinstan.springview:library:1.2.6'
//权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 网络状态 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
drawable文件夹
btn_bg_red
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ff5a09"/>
<corners android:topLeftRadius="20dip"
android:topRightRadius="20dip"
android:bottomRightRadius="20dip"
android:bottomLeftRadius="20dip" />
</shape>
shape
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="20dp"/>
<solid android:color="#EEEEEE"/>
</shape>
下面是布局
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.bw.arp.moni_demo.util.MyTitleview
android:id="@+id/main_mytitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"></com.bw.arp.moni_demo.util.MyTitleview>
<com.fynn.fluidlayout.FluidLayout
android:id="@+id/fluidLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/btn_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="清除历史记录" />
</LinearLayout>
activity_shop_car
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.bw.arp.moni_demo.ShopCarActivity">
<include
layout="@layout/header_car"
/>
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swip"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<ExpandableListView
android:id="@+id/shop_car_elv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</android.support.v4.widget.SwipeRefreshLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="2dp"
android:background="#7f000000"
/>
<include
layout="@layout/footer_car"
/>
</LinearLayout>
footer_car
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<CheckBox
android:id="@+id/ck_All"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="10dp"
android:text="全选"
/>
<TextView
android:id="@+id/sumprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_weight="1"
android:padding="10dp"
android:gravity="center"
android:text="合计:¥0.00"
/>
<TextView
android:id="@+id/account"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结算:(0)"
android:textSize="20sp"
android:textColor="#fff"
android:padding="10dp"
android:gravity="center"
android:background="#f23030"
/>
</LinearLayout>
header_car
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f23030"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="10dp"
android:layout_weight="1"
android:text="购物车"
android:textColor="#fff"
android:layout_centerInParent="true"
/>
<TextView
android:id="@+id/tv_redact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="10dp"
android:text="编辑"
android:layout_alignParentRight="true"
android:textColor="#fff"
/>
</RelativeLayout>
layout_child_item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/ck_child_choose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleX="0.6"
android:scaleY="0.6" />
<ImageView
android:id="@+id/iv_show_pic"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:src="@mipmap/ic_launcher"
android:layout_toRightOf="@id/ck_child_choose" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:layout_toRightOf="@id/iv_show_pic"
android:orientation="vertical">
<TextView
android:id="@+id/tv_commodity_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="酒红色纯红色纯羊毛西服套装"
android:textColor="@android:color/black"
android:textSize="12sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_commodity_attr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="属性:粉蓝色"
android:textSize="12sp"
android:textColor="@color/colorPrimary" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_commodity_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="¥390"
android:textColor="@android:color/holo_red_dark"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_commodity_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="x1"
android:textColor="@android:color/darker_gray" />
<LinearLayout
android:id="@+id/rl_edit"
android:layout_width="120dp"
android:background="@android:color/holo_orange_light"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
>
<TextView
android:id="@+id/iv_sub"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:textColor="@android:color/black"
android:background="@android:color/white"
android:layout_margin="1dp"
android:layout_height="match_parent"
android:text=" - " />
<TextView
android:id="@+id/tv_commodity_show_num"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:background="@android:color/white"
android:layout_margin="1dp"
android:layout_height="match_parent"
android:text="1"
/>
<TextView
android:id="@+id/iv_add"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_margin="1dp"
android:background="@android:color/white"
android:layout_height="match_parent"
android:text=" + " />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/btn_commodity_delete"
android:layout_width="50dp"
android:layout_height="90dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="删除"
android:background="#f00"
android:textColor="#fff"
android:visibility="gone"
/>
</RelativeLayout>
layout_group_item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<CheckBox
android:id="@+id/ck_group_choose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="店铺"
android:gravity="center_vertical"
android:textSize="25sp"
android:focusable="false"
android:padding="10dp"/>
</LinearLayout>
sousuo_item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<LinearLayout
android:layout_marginTop="3dp"
android:layout_width="50dp"
android:paddingTop="10dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/back"
/>
</LinearLayout>
<LinearLayout
android:layout_marginTop="8dp"
android:paddingTop="10dp"
android:gravity="center_vertical"
android:layout_width="250dp"
android:layout_height="35dp"
android:background="@drawable/shape">
<EditText
android:id="@+id/edit_sou"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:background="@drawable/shape"
android:textColor="#000"
android:textSize="12dp"
android:hint="iphone 10 手机" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:background="@mipmap/camera"
android:layout_marginRight="13dp"
android:layout_marginTop="-5dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="@+id/main_bt_sou"
android:layout_width="60dp"
android:layout_height="30dp"
android:background="@drawable/btn_bg_red"
android:text="搜索"
android:textColor="#fff"
android:layout_marginTop="10dp"
/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
下面是代码
adapter文件夹
MyElvAdapter
public class MyElvAdapter extends BaseExpandableListAdapter {
private List<ShoppingBean.DataBean> list;
private Context context;
private Button btn_commodity_delete;
private String pid;
public void setList(List<ShoppingBean.DataBean> list) {
this.list = list;
notifyDataSetChanged();
}
public MyElvAdapter(Context context) {
this.context = context;
}
//接收是否处于编辑状态的一个boolean值
private boolean isEditor;
private CheckGroupItemListener checkGroupItemListener;
private ModifyGoodsItemNumberListener modifyGoodsItemNumberListener;
//删除商品
private DeleteItemLinister deleteItemLinister;
//更新购物车
private UpdateItemLinister updateItemLinister;
public void setUpdateItemLinister(UpdateItemLinister updateItemLinister) {
this.updateItemLinister = updateItemLinister;
}
public void setDeleteItemLinister(DeleteItemLinister deleteItemLinister) {
this.deleteItemLinister = deleteItemLinister;
}
public void setCheckGroupItemListener(CheckGroupItemListener checkGroupItemListener) {
this.checkGroupItemListener = checkGroupItemListener;
}
public void setModifyGoodsItemNumberListener(ModifyGoodsItemNumberListener modifyGoodsItemNumberListener) {
this.modifyGoodsItemNumberListener = modifyGoodsItemNumberListener;
}
//是否显示删除按钮
public void showDeleteButton(boolean isEditor){
this.isEditor = isEditor;
//刷新适配器
notifyDataSetChanged();
}
@Override
public int getGroupCount() {
return list != null ? list.size() : 0;
}
@Override
public int getChildrenCount(int i) {
return list != null && list.get(i).getList() != null ? list.get(i).getList().size() : 0;
}
@Override
public Object getGroup(int i) {
return list.get(i);
}
@Override
public Object getChild(int i, int i1) {
return list.get(i).getList().get(i1);
}
@Override
public long getGroupId(int i) {
return i;
}
@Override
public long getChildId(int i, int i1) {
return i1;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
if (view==null){
view= LayoutInflater.from(context).inflate(R.layout.layout_group_item,viewGroup,false);
}
CheckBox ck_group_choose = view.findViewById(R.id.ck_group_choose);
//设置商家的CheckBox
if (list.get(i).isGroupChoosed()){
ck_group_choose.setChecked(true);
}else {
ck_group_choose.setChecked(false);
}
//点击
ck_group_choose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkGroupItemListener.checkGroupItem(i,((CheckBox)view).isChecked());
}
});
//最后赋值
ck_group_choose.setText(list.get(i).getSellerName());
return view;
}
@Override
public View getChildView(final int i, final int i1, boolean b, View convertView, ViewGroup viewGroup) {
pid = list.get(i).getList().get(i1).getPid();
if (convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.layout_child_item,viewGroup,false);
}
//商品选择
CheckBox ck_child_choosed = convertView.findViewById(R.id.ck_child_choose);
//商品图片
ImageView iv_show_pic = convertView.findViewById(R.id.iv_show_pic);
//商品主标题
TextView tv_commodity_name = convertView.findViewById(R.id.tv_commodity_name);
//商品副标题
TextView tv_commodity_attr = convertView.findViewById(R.id.tv_commodity_attr);
//商品价格
TextView tv_commodity_price = convertView.findViewById(R.id.tv_commodity_price);
//商品数量
TextView tv_commodity_num = convertView.findViewById(R.id.tv_commodity_num);
//商品减
TextView iv_sub = convertView.findViewById(R.id.iv_sub);
//商品加减中的数量变化
final TextView tv_commodity_show_num = convertView.findViewById(R.id.tv_commodity_show_num);
//商品加
TextView iv_add = convertView.findViewById(R.id.iv_add);
//删除按钮
btn_commodity_delete = convertView.findViewById(R.id.btn_commodity_delete);
//设置文本信息
tv_commodity_name.setText(list.get(i).getList().get(i1).getTitle());
tv_commodity_attr.setText(list.get(i).getList().get(i1).getSubhead());
tv_commodity_price.setText("¥"+list.get(i).getList().get(i1).getPrice());
tv_commodity_num.setText("x"+list.get(i).getList().get(i1).getNum());
tv_commodity_show_num.setText(list.get(i).getList().get(i1).getNum()+"");
//图片分割
String images = list.get(i).getList().get(i1).getImages();
String[] urls = images.split("\\|");
//加载图片
Glide.with(context)
.load(urls[0])
.crossFade()
.into(iv_show_pic);
//商品加
iv_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.doIncrease(i,i1,tv_commodity_show_num);
}
});
//商品减
iv_sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.doDecrease(i,i1,tv_commodity_show_num);
}
});
//商品复选框是否被选中
ck_child_choosed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkGroupItemListener.checkChildItem(i,i1,((CheckBox)view).isChecked());
}
});
//处理商品的选中状态
if (list.get(i).getList().get(i1).isChildChoosed()){
ck_child_choosed.setChecked(true);
}else {
ck_child_choosed.setChecked(false);
}
//控制删除按钮的隐藏与显示
if (isEditor){
btn_commodity_delete.setVisibility(View.VISIBLE);
}else {
btn_commodity_delete.setVisibility(View.GONE);
}
btn_commodity_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示");
builder.setMessage("确定删除此商品吗?");
builder.setNegativeButton("取消",null);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteItemLinister.doDelete(pid,view,i,i1);
notifyDataSetChanged();
// btn_commodity_delete.setVisibility(View.GONE);
}
});
//显示!!!
builder.show();
}
});
return convertView;
}
@Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
//购物车逻辑实现
/**
* 商家的复选框以及商品的复选框是否被选中的接口
*/
/**
* 商家复选框以及商品复选框是否被选中接口
*/
public interface CheckGroupItemListener{
//商家的条目的复选框监听
void checkGroupItem(int groupPosition,boolean isChecked);
//商品的
void checkChildItem(int groupPosition,int childPosition,boolean isChecked);
}
/**
* 商品加减接口
*/
public interface ModifyGoodsItemNumberListener{
//商品添加操作
void doIncrease(int groupPosition,int childPosition,View view);
//商品减少操作
void doDecrease(int groupPosition,int childPosition,View view);
}
/**
* 商品删除接口
*/
public interface DeleteItemLinister{
//删除
void doDelete(String pid,View view,int i,int i1);
}
/**
* 商品删除接口
*/
public interface UpdateItemLinister{
//更新购物车
void doUpdate(String sellerid,String pid,String selected,String num,View view,int i,int i1);
}
}
bean文件夹
DeleteBean
public class DeleteBean {
/**
* msg : 删除购物车成功
* code : 0
*/
private String msg;
private String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
这里是greendao
KeywordBean
@Entity
public class KeywordBean {
@Id(autoincrement = true)
private Long id;
private String name;
@Generated(hash = 138641661)
public KeywordBean(Long id, String name) {
this.id = id;
this.name = name;
}
@Generated(hash = 1737222118)
public KeywordBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
ShoppingBean
public class ShoppingBean {
private String msg;
private String code;
private List<DataBean> data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String sellerName;
private String sellerid;
private List<ListBean> list;
//商家是否被选中 组条目是否被选中
private boolean isGroupChoosed;
public boolean isGroupChoosed() {
return isGroupChoosed;
}
public void setGroupChoosed(boolean groupChoosed) {
isGroupChoosed = groupChoosed;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getSellerid() {
return sellerid;
}
public void setSellerid(String sellerid) {
this.sellerid = sellerid;
}
public List<ListBean> getList() {
return list;
}
public void setList(List<ListBean> list) {
this.list = list;
}
public static class ListBean {
private double bargainPrice;
private String createtime;
private String detailUrl;
private String images;
private int num;
private String pid;
private double price;
private int pscid;
private int selected;
private int sellerid;
private String subhead;
private String title;
//子条目商品是否被选中的一个字段状态
private boolean isChildChoosed;
public boolean isChildChoosed() {
return isChildChoosed;
}
public void setChildChoosed(boolean childChoosed) {
isChildChoosed = childChoosed;
}
public double getBargainPrice() {
return bargainPrice;
}
public void setBargainPrice(double bargainPrice) {
this.bargainPrice = bargainPrice;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getDetailUrl() {
return detailUrl;
}
public void setDetailUrl(String detailUrl) {
this.detailUrl = detailUrl;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPscid() {
return pscid;
}
public void setPscid(int pscid) {
this.pscid = pscid;
}
public int getSelected() {
return selected;
}
public void setSelected(int selected) {
this.selected = selected;
}
public int getSellerid() {
return sellerid;
}
public void setSellerid(int sellerid) {
this.sellerid = sellerid;
}
public String getSubhead() {
return subhead;
}
public void setSubhead(String subhead) {
this.subhead = subhead;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
}
greendemo文件夹
DaoMaster
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
KeywordBeanDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
KeywordBeanDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(KeywordBeanDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}
DaoSession
public class DaoSession extends AbstractDaoSession {
private final DaoConfig keywordBeanDaoConfig;
private final KeywordBeanDao keywordBeanDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
keywordBeanDaoConfig = daoConfigMap.get(KeywordBeanDao.class).clone();
keywordBeanDaoConfig.initIdentityScope(type);
keywordBeanDao = new KeywordBeanDao(keywordBeanDaoConfig, this);
registerDao(KeywordBean.class, keywordBeanDao);
}
public void clear() {
keywordBeanDaoConfig.clearIdentityScope();
}
public KeywordBeanDao getKeywordBeanDao() {
return keywordBeanDao;
}
}
KeywordBeanDao
public class KeywordBeanDao extends AbstractDao<KeywordBean, Long> {
public static final String TABLENAME = "KEYWORD_BEAN";
/**
* Properties of entity KeywordBean.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Name = new Property(1, String.class, "name", false, "NAME");
}
public KeywordBeanDao(DaoConfig config) {
super(config);
}
public KeywordBeanDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"KEYWORD_BEAN\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id
"\"NAME\" TEXT);"); // 1: name
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"KEYWORD_BEAN\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, KeywordBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, KeywordBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(2, name);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public KeywordBean readEntity(Cursor cursor, int offset) {
KeywordBean entity = new KeywordBean( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1) // name
);
return entity;
}
@Override
public void readEntity(Cursor cursor, KeywordBean entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
}
@Override
protected final Long updateKeyAfterInsert(KeywordBean entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(KeywordBean entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(KeywordBean entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
model文件夹
DeleteModel
public class DeleteModel {
private Context context;
public void getdeletedata(String uid, String pid, final IDeletePresenter iDeletePresenter){
DataManager manager = new DataManager(context);
CompositeSubscription subscription = new CompositeSubscription();
subscription.add(
manager.getdelete(uid, pid)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<DeleteBean>() {
@Override
public void onCompleted() {
Log.e("onCompleted","onCompleted");
}
@Override
public void onError(Throwable e) {
Log.e("onError",e.getMessage());
}
@Override
public void onNext(DeleteBean deleteBean) {
Log.e("onNext","onNext");
iDeletePresenter.Show(deleteBean);
}
})
);
}
}
ShopCarModel
public class ShopCarModel {
private Context context;
public void getshopcardata(String uid, String source, final IShopCarPresenter iShopCarPresenter){
DataManager manager = new DataManager(context);
CompositeSubscription subscription = new CompositeSubscription();
subscription.add(
manager.getshoppingcar(uid,source)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ShoppingBean>() {
@Override
public void onCompleted() {
Log.e("onCompleted","onCompleted");
}
@Override
public void onError(Throwable e) {
Log.e("onError",e.getMessage());
}
@Override
public void onNext(ShoppingBean shoppingBean) {
Log.e("onNext","onNext");
iShopCarPresenter.Show(shoppingBean);
}
})
);
}
}
presenter文件夹
DeletePresenter
public class DeletePresenter implements IDeletePresenter{
private IDeleteView iDeleteView;
private DeleteModel deleteModel;
public DeletePresenter(IDeleteView iDeleteView) {
this.iDeleteView = iDeleteView;
this.deleteModel = new DeleteModel();
}
public void getDeleteData(String uid,String pid){
deleteModel.getdeletedata(uid,pid,this);
}
@Override
public void Show(DeleteBean deleteBean) {
iDeleteView.onSuccess(deleteBean);
}
@Override
public void deView() {
if (iDeleteView!=null){
iDeleteView = null;
}
}
}
IDeletePresenter
public interface IDeletePresenter {
void Show(DeleteBean deleteBean);
void deView();
}
IShopCarPresenter
public interface IShopCarPresenter {
void Show(ShoppingBean shoppingBean);
void detachView();
}
ShopCarPresenter
public class ShopCarPresenter implements IShopCarPresenter{
private ShopCarModel shopCarModel;
private IShopCarView iShopCarView;
public ShopCarPresenter(IShopCarView iShopCarView) {
this.iShopCarView = iShopCarView;
this.shopCarModel = new ShopCarModel();
}
public void getShopCarDatas(String uid,String source){
shopCarModel.getshopcardata(uid,source,this);
}
@Override
public void Show(ShoppingBean shoppingBean) {
iShopCarView.onSuccess(shoppingBean);
}
@Override
public void detachView() {
if (iShopCarView!=null){
iShopCarView = null;
}
}
}
util文件夹
DataManager
public class DataManager {
private RetrofitService mRetrofitService;
//构造器里获取RetrofitService
public DataManager(Context context) {
this.mRetrofitService = RetrofitHelper.getInstance(context).getServer();
}
//查询购物车
public Observable<ShoppingBean> getshoppingcar(String uid,String source){
return mRetrofitService.shoppingcar(uid, source);
}
//删除购物车条目
public Observable<DeleteBean> getdelete(String uid,String pid){
return mRetrofitService.delete(uid,pid);
}
}
MyApp
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
}
}
MyTitleview
public class MyTitleview extends RelativeLayout {
private EditText edit_sou;
private Button main_bt_sou;
public MyTitleview(Context context) {
this(context, null);
}
public MyTitleview(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTitleview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(final Context context, AttributeSet attrs) {
View inflate = View.inflate(context, R.layout.sousuo_item, this);
edit_sou = inflate.findViewById(R.id.edit_sou);
main_bt_sou = inflate.findViewById(R.id.main_bt_sou);
main_bt_sou.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String keywords = edit_sou.getText().toString().trim();
// Toast.makeText(context,keywords+"",Toast.LENGTH_SHORT).show();
listened.toString(keywords);
edit_sou.setText("");
}
});
}
Listened listened;
public void setListened(Listened listened){
this.listened=listened;
}
public interface Listened{
void toString(String editText);
}
}
RetrofitHelper
public class RetrofitHelper {
public Context mCntext;
//初始化
OkHttpClient interceptor = new OkHttpClient();
//gson工厂
GsonConverterFactory factory = GsonConverterFactory.create(new GsonBuilder().create());
private static RetrofitHelper instance = null;
private Retrofit mRetrofit = null;
//单例模式
public static RetrofitHelper getInstance(Context context){
if (instance == null){
instance = new RetrofitHelper(context);
}
return instance;
}
private RetrofitHelper(Context mContext){
mCntext = mContext;
init();
}
private void init() {
resetApp();
}
private void resetApp() {
//拦截器
HttpLoggingInterceptor interceptor1 = new HttpLoggingInterceptor();
interceptor1.setLevel(HttpLoggingInterceptor.Level.BASIC);
//初始化retrofit
mRetrofit = new Retrofit.Builder()
.baseUrl("http://120.27.23.105/")
.client(interceptor)
.addConverterFactory(factory)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
public RetrofitService getServer(){
return mRetrofit.create(RetrofitService.class);
}
}
RetrofitService
public interface RetrofitService {
//查询购物车数据
@GET("product/getCarts")
Observable<ShoppingBean> shoppingcar(@Query("uid") String uid,
@Query("source") String source
);
//删除购物车
@GET("product/deleteCart")
Observable<DeleteBean> delete(@Query("uid") String uid,
@Query("pid") String pid
);
}
view文件夹
IDeleteView
public interface IDeleteView {
//成功
void onSuccess(DeleteBean deleteBean);
//失败
void onFailed(Exception e);
}
IShopCarView
public interface IShopCarView {
//成功
void onSuccess(ShoppingBean shoppingBean);
//失败
void onFailed(Exception e);
}
单独的
MainActivity
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.bw.arp.moni_demo.bean.KeywordBean;
import com.bw.arp.moni_demo.greendemo.DaoMaster;
import com.bw.arp.moni_demo.greendemo.DaoSession;
import com.bw.arp.moni_demo.greendemo.KeywordBeanDao;
import com.bw.arp.moni_demo.util.MyTitleview;
import com.fynn.fluidlayout.FluidLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.main_mytitle)
MyTitleview mMainMytitle;
@BindView(R.id.fluidLayout)
FluidLayout mFluidLayout;
@BindView(R.id.btn_all)
TextView mBtnAll;
private KeywordBeanDao keywordBeanDao;
private List<KeywordBean> stringlist = new ArrayList<>();
private long exitTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//实例化GreenDao
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "pwk.db", null);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
keywordBeanDao = daoSession.getKeywordBeanDao();
mMainMytitle.setListened(new MyTitleview.Listened() {
@Override
public void toString(String editText) {
// Toast.makeText(MainActivity.this,editText+"",Toast.LENGTH_SHORT).show();
if (!TextUtils.isEmpty(editText)) {
keywordBeanDao.insertOrReplaceInTx(new KeywordBean(null, editText));
genTag();
startActivity(new Intent(MainActivity.this,ShopCarActivity.class));
// mBtnAll.setVisibility(View.VISIBLE);
}else
Toast.makeText(MainActivity.this,"输入内容为空",Toast.LENGTH_SHORT).show();
}
});
mBtnAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("提示!");
builder.setMessage("确定要删除历史记录吗?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
keywordBeanDao.deleteAll();
genTag();
}
});
builder.setNegativeButton("取消",null);
builder.show();
}
});
genTag();
}
private void genTag() {
List<KeywordBean> beans = keywordBeanDao.loadAll();
stringlist.clear();
stringlist.addAll(beans);
mFluidLayout.removeAllViews();
for (int x = 0; x < beans.size(); x++) {
TextView tv = new TextView(MainActivity.this);
tv.setText(stringlist.get(x).getName());
tv.setTextSize(13);
FluidLayout.LayoutParams params = new FluidLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(12, 12, 12, 12);
mFluidLayout.addView(tv, params);
}
}
//用户退出程序 2
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
if ((System.currentTimeMillis()-exitTime)>2000){
Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
}else {
finish();
// System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
ShopCarActivity
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import com.bw.arp.moni_demo.adapter.MyElvAdapter;
import com.bw.arp.moni_demo.bean.DeleteBean;
import com.bw.arp.moni_demo.bean.ShoppingBean;
import com.bw.arp.moni_demo.presenter.DeletePresenter;
import com.bw.arp.moni_demo.presenter.ShopCarPresenter;
import com.bw.arp.moni_demo.view.IDeleteView;
import com.bw.arp.moni_demo.view.IShopCarView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.subscriptions.CompositeSubscription;
public class ShopCarActivity extends AppCompatActivity implements IShopCarView, MyElvAdapter.CheckGroupItemListener, MyElvAdapter.ModifyGoodsItemNumberListener, IDeleteView {
@BindView(R.id.shop_car_elv)
ExpandableListView mShopCarElv;
@BindView(R.id.tv_redact)
TextView mTvRedact;
@BindView(R.id.ck_All)
CheckBox mCkAll;
@BindView(R.id.sumprice)
TextView mSumprice;
@BindView(R.id.account)
TextView mAccount;
@BindView(R.id.swip)
SwipeRefreshLayout mSwip;
//默认是false
private boolean flag;
//购买商品的总价
private double totalPrice = 0.00; //15.55 15 0.55亿
//购买商品的总数量
private int totalNum = 0;
private ShopCarPresenter shopCarPresenter;
private MyElvAdapter adapter;
private List<ShoppingBean.DataBean> list = new ArrayList<>();
private DeletePresenter deletePresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop_car);
ButterKnife.bind(this);
//实例化购物车的P层
shopCarPresenter = new ShopCarPresenter(this);
shopCarPresenter.getShopCarDatas("10234", "android");
adapter = new MyElvAdapter(this);
mShopCarElv.setAdapter(adapter);
//去除默认显示器
mShopCarElv.setGroupIndicator(null);
//加减
adapter.setModifyGoodsItemNumberListener(this);
//全选
adapter.setCheckGroupItemListener(this);
mCkAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isChoosedAll(((CheckBox) view).isChecked());
//总价
statisticsPrice();
}
});
mTvRedact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!flag) {//编辑 -> 完成\
flag = true;
mTvRedact.setText("完成");
adapter.showDeleteButton(flag);
} else {
flag = false;
mTvRedact.setText("编辑");
adapter.showDeleteButton(flag);
}
}
});
//实例化删除P层
deletePresenter = new DeletePresenter(this);
//结算按钮
mAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ShopCarActivity.this,"结算成功",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onSuccess(ShoppingBean shoppingBean) {
list.addAll(shoppingBean.getData());
adapter.setList(list);
defaultExpand();
adapter.setDeleteItemLinister(new MyElvAdapter.DeleteItemLinister() {
@Override
public void doDelete(String pid, View view, int i, int i1) {
deletePresenter.getDeleteData("10234", pid);
adapter.notifyDataSetChanged();
}
});
//下拉更新购物车
mSwip.setColorSchemeColors(Color.GRAY);
mSwip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mSwip.setRefreshing(false);
list.clear();
shopCarPresenter.getShopCarDatas("10234", "android");
Toast.makeText(ShopCarActivity.this,"刷新成功",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onSuccess(DeleteBean deleteBean) {
Toast.makeText(this, deleteBean.getMsg(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailed(Exception e) {
}
//二级列表默认展开
private void defaultExpand() {
for (int i = 0; i < adapter.getGroupCount(); ++i) {
mShopCarElv.expandGroup(i);
}
}
@Override
public void checkGroupItem(int groupPosition, boolean isChecked) {
//商家javabean
ShoppingBean.DataBean dataBean = list.get(groupPosition);
dataBean.setGroupChoosed(isChecked);
//遍历商家里面的商品,将其置为选中状态
for (ShoppingBean.DataBean.ListBean listBean : dataBean.getList()) {
listBean.setChildChoosed(isChecked);
}
//底部结算那个checkbox状态(全选)
if (isCheckAll()) {
mCkAll.setChecked(true);
} else {
mCkAll.setChecked(false);
}
//刷新适配器
adapter.notifyDataSetChanged();
//计算价格
statisticsPrice();
}
@Override
public void checkChildItem(int groupPosition, int childPosition, boolean isChecked) {
ShoppingBean.DataBean dataBean = list.get(groupPosition);//商家那一层
List<ShoppingBean.DataBean.ListBean> listBeans = dataBean.getList();
ShoppingBean.DataBean.ListBean listBean = listBeans.get(childPosition);
//你点击商家的商品条目将其选中状态记录
listBean.setChildChoosed(isChecked);
//检测商家里面的每一个商品是否被选中,如果被选中,返回boolean
boolean result = isGoodsCheckAll(groupPosition);
if (result) {
dataBean.setGroupChoosed(result);
} else {
dataBean.setGroupChoosed(result);
}
//底部结算那个checkbox状态(全选)
if (isCheckAll()) {
mCkAll.setChecked(true);
} else {
mCkAll.setChecked(false);
}
//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
statisticsPrice();
}
@Override
public void doIncrease(int groupPosition, int childPosition, View view) {
ShoppingBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
//取出当前的商品数量
int currentNum = listBean.getNum();
//商品++
currentNum++;
//将商品数量设置javabean上
listBean.setNum(currentNum);
//刷新适配器
adapter.notifyDataSetChanged();
//计算商品价格
statisticsPrice();
}
@Override
public void doDecrease(int groupPosition, int childPosition, View view) {
ShoppingBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
//取出当前的商品数量
int currentNum = listBean.getNum();
//直接结束这个方法
if (currentNum == 1) {
Toast.makeText(this, "商品最小数量为1", Toast.LENGTH_SHORT).show();
return;
}
currentNum--;
listBean.setNum(currentNum);
//刷新适配器
adapter.notifyDataSetChanged();
//计算商品价格
statisticsPrice();
}
//逻辑实行
/**
* 检测某个商家的商品是否都选中,如果都选中的话,商家CheckBox应该是选中状态
*
* @param groupPosition
* @return
*/
private boolean isGoodsCheckAll(int groupPosition) {
List<ShoppingBean.DataBean.ListBean> listBeans = this.list.get(groupPosition).getList();
//遍历某一个商家的每个商品是否被选中
for (ShoppingBean.DataBean.ListBean listBean : listBeans) {
if (listBean.isChildChoosed()) {//是选中状态
continue;
} else {
return false;
}
}
return true;
}
//购物车商品是否全部选中
private boolean isCheckAll() {
for (ShoppingBean.DataBean dataBean : list) {
if (!dataBean.isGroupChoosed()) {
return false;
}
}
return true;
}
//全选与反选
private void isChoosedAll(boolean isChecked) {
for (ShoppingBean.DataBean dataBean : list) {
dataBean.setGroupChoosed(isChecked);
for (ShoppingBean.DataBean.ListBean listBean : dataBean.getList()) {
listBean.setChildChoosed(isChecked);
}
}
//刷新适配器
adapter.notifyDataSetChanged();
}
/**
* 计算你所选中的商品总价
*/
private void statisticsPrice() {
//初始化值
totalNum = 0;
totalPrice = 0.00;
for (ShoppingBean.DataBean dataBean : list) {
for (ShoppingBean.DataBean.ListBean listBean : dataBean.getList()) {
if (listBean.isChildChoosed()) {
totalNum++;
System.out.println("number : " + totalNum);
totalPrice += listBean.getNum() * listBean.getPrice();
}
}
}
//设置文本信息 合计、结算的商品数量
mSumprice.setText("合计:¥" + totalPrice);
mAccount.setText("结算(" + totalNum + ")");
}
//内存优化
@Override
protected void onDestroy() {
super.onDestroy();
if (shopCarPresenter!=null){
shopCarPresenter.detachView();
shopCarPresenter=null;
}
//解绑
CompositeSubscription subscription = new CompositeSubscription();
subscription.unsubscribe();
}
}