安卓开发|购物车操作增删改查

MainActivity

private TextView shoppingcart_text; private RelativeLayout relativelayout; private ExpandableListView expandableListView; private CheckBox checkAll; private TextView sun; private Button shancuh; private Button goumai; private RelativeLayout relative; private GetCartPresenter getCartPresenter; private QueryBean queryBean; //定义handler @SuppressLint("HandlerLeak") Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 0) { countPriceBean = (CountPriceBean) msg.obj; //设置总金额 sun.setText(countPriceBean.getPriceString()); }else if(msg.what==1){ QueryBean queryBean = (QueryBean) msg.obj; Log.d("TAG","Tag+++++++++++++"+queryBean); //判断当前所有子条目是否选中来决定一组的选中状态 for (int i = 0; i < queryBean.getData().size(); i++) { if (ischilditemcheck(i)) { //如果子条目都选中为,true queryBean.getData().get(i).setGroupChecked(true); } }//判断所有组是不是选中,来显示全选是不是选中 checkAll.setChecked(ischeclAll()); //设置适配器 if (queryBean!=null){myAdapter = new MyAdapter(MainActivity.this, queryBean,handler,getCartPresenter,sp); expandableListView.setAdapter(myAdapter); }//展开组 for (int i=0; i(); params.put("uid","4575"); params.put("pid", String.valueOf(queryBean.getData().get(i).getList().get(j).getPid())); RetrofitUtil.delcards(params, new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()){ getCartPresenter.getNetWrok(); } }@Override public void onFailure(Call call, Throwable t) {} }); } } }break; case R.id.goumai:break; case R.id.checkAll: Log.i("tag","tagtagtagtagtagtagtagtagtag"); myAdapter.setAllChildState(checkAll.isChecked()); ischeclAll(); break; } }@Override public void onSeccess(QueryBean queryBean) { if (queryBean!=null){ this.queryBean = queryBean; Message msg = Message.obtain(); msg.what=1; msg.obj=queryBean; handler.sendMessage(msg); }else{ Toast.makeText(MainActivity.this,"购物车为空",Toast.LENGTH_SHORT).show(); } }//判断当前子条目的选中状态 private boolean ischilditemcheck(int groupposition) { for (int i=0; i

Activity布局


适配器
import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.drawee.view.SimpleDraweeView; import com.luobing.jinjieweek2.R; import com.luobing.jinjieweek2.model.bean.CountPriceBean; import com.luobing.jinjieweek2.model.bean.QueryBean; import com.luobing.jinjieweek2.model.bean.UpdataBean; import com.luobing.jinjieweek2.model.util.RetrofitUtil; import com.luobing.jinjieweek2.presenter.GetCartPresenter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Administrator on 2018/1/6. */public class MyAdapter extends BaseExpandableListAdapter{ Context context; QueryBean getCartBean; Handler handler; int childI; private int child_size; GetCartPresenter getCartPresenter; private int childitemListSize; private int index; private SharedPreferences sp; final String uid ="4575"; // public MyAdapter(Context context, QueryBean getCartBean, Handler handler, GetCartPresenter getCartPresenter, SharedPreferences sp) { this.context=context; this.getCartBean=getCartBean; this.handler=handler; this.getCartPresenter=getCartPresenter; this.sp=sp; }@Override public int getGroupCount() { return getCartBean.getData().size(); }@Override public int getChildrenCount(int groupPosition) { return getCartBean.getData().get(groupPosition).getList().size(); }@Override public Object getGroup(int groupPosition) { return getCartBean.getData().get(groupPosition); }@Override public Object getChild(int groupPosition, int childPosition) { return getCartBean.getData().get(groupPosition).getList().get(childPosition); }@Override public long getGroupId(int groupPosition) { return groupPosition; }@Override public long getChildId(int groupPosition, int childPosition) { return childPosition; }@Override public boolean hasStableIds() { return true; }@Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; }//查找group一级控件的方法 @Override public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {//获得集合 final List data = https://www.it610.com/article/getCartBean.getData(); final GroupHolder groupHolder; if (view==null){ view = View.inflate(context, R.layout.group_item_layout,null); groupHolder = new GroupHolder(); groupHolder.check_group=view.findViewById(R.id.group_check); groupHolder.text_group=view.findViewById(R.id.group_text_title); view.setTag(groupHolder); }else{ groupHolder = (GroupHolder) view.getTag(); }//找到集合中的一个 final QueryBean.DataBean dataBean = data.get(groupPosition); //赋值 groupHolder.check_group.setChecked(dataBean.isGroupChecked()); groupHolder.text_group.setText(dataBean.getSellerName()); //设置一级的点击事件 groupHolder.check_group.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {child_size = dataBean.getList().size(); childI = 0; //更新购物车 updateAllInGroup(groupHolder.check_group.isChecked(),dataBean); } }); return view; }//更新购物车的方法 public void updateAllInGroup(final boolean checked, final QueryBean.DataBean dataBean) { //拿到子条目集合 QueryBean.DataBean.ListBean listBean = dataBean.getList().get(childI); Map params = new HashMap<>(); params.put("uid","4575"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(checked? 1:0)); RetrofitUtil.updatacards(params,new retrofit2.Callback() { @Override public void onResponse(retrofit2.Call call, retrofit2.Response response) { if (response.isSuccessful()){ childI=childI+1; //如果小于,则递归 if (childI call, Throwable t) {} }); }//查找child二级控件的方法 @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {final ChildHolder childHolder; if (view == null) { view = View.inflate(context, R.layout.child_item_layout, null); childHolder = new ChildHolder(); childHolder.check_child = view.findViewById(R.id.child_check); childHolder.simpleDraweeView = view.findViewById(R.id.simpleDraweeView); childHolder.text_title = view.findViewById(R.id.child_tetle); childHolder.text_price = view.findViewById(R.id.text_price); childHolder.text_jian = view.findViewById(R.id.child_jian); childHolder.text_add = view.findViewById(R.id.child_add); childHolder.text_num = view.findViewById(R.id.child_num); childHolder.linearLayout=view.findViewById(R.id.bianji_layout); childHolder.text_bianji=view.findViewById(R.id.bianjibtn); childHolder.addjian=view.findViewById(R.id.addjian); childHolder.text_datermine = view.findViewById(R.id.datermine); childHolder.text_child_shuliang = view.findViewById(R.id.child_shuliang); //复用 view.setTag(childHolder); } else { childHolder = (ChildHolder) view.getTag(); } boolean flag = sp.getBoolean("flag", false); if(flag){ childHolder.linearLayout.setVisibility(View.VISIBLE); childHolder.addjian.setVisibility(View.GONE); }else{ childHolder.linearLayout.setVisibility(View.GONE); childHolder.addjian.setVisibility(View.VISIBLE); }final QueryBean.DataBean.ListBean listBean = getCartBean.getData().get(groupPosition).getList().get(childPosition); //赋值 childHolder.text_title.setText(listBean.getTitle()); childHolder.text_price.setText(listBean.getBargainPrice()+""); childHolder.text_num.setText(listBean.getNum()+""); childHolder.text_child_shuliang.setText(listBean.getNum()+""); childHolder.check_child.setChecked(listBean.getSelected()==0? false:true); Uri uri = Uri.parse(listBean.getImages().split("\\|")[0]); childHolder.simpleDraweeView.setImageURI(uri); //设置编辑的点击事件 childHolder.text_bianji.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { childHolder.linearLayout.setVisibility(View.GONE); childHolder.addjian.setVisibility(View.VISIBLE); SharedPreferences.Editor edit = sp.edit(); edit.putBoolean("flag",false); edit.commit(); } }); //编辑之后确定的点击事件 childHolder.text_datermine.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { childHolder.linearLayout.setVisibility(View.VISIBLE); childHolder.addjian.setVisibility(View.GONE); SharedPreferences.Editor edit = sp.edit(); edit.putBoolean("flag",true); edit.commit(); } }); //设置点击事件 childHolder.check_child.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateCart(listBean,true,false); } }); //减号 childHolder.text_jian.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listBean.getNum()==1){ return; }else{ updateCart(listBean,false,false); } } }); //加号 childHolder.text_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { updateCart(listBean,false,true); } }); return view; }//更新购物车的 private void updateCart(QueryBean.DataBean.ListBean listBean, boolean upstate, boolean addorjian) { Map params = new HashMap<>(); params.put("uid","4575"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(listBean.getSelected())); Toast.makeText(context,"当前状态"+upstate,Toast.LENGTH_SHORT).show(); params.put("num",listBean.getNum()+""); if (upstate){ params.put("selected", String.valueOf(listBean.getSelected()==0? 1:0)); }else{if (addorjian){ params.put("num",listBean.getNum()+1+""); }else{ params.put("num",listBean.getNum()-1+""); } }RetrofitUtil.updatacards(params, new retrofit2.Callback() { @Override public void onResponse(retrofit2.Call call, retrofit2.Response response) { if (response.isSuccessful()){ getCartPresenter.getNetWrok(); } }@Override public void onFailure(retrofit2.Call call, Throwable t) {} }); }/** * 计算价格和数量 并发送显示 */ public void sendPriceAndCount() {double price = 0; int count = 0; //通过判断二级列表是否勾选,,,,计算价格数量 for (int i=0; i allList = new ArrayList<>(); for (int i=0; i allList, final boolean checked) {QueryBean.DataBean.ListBean listBean = allList.get(index); //0//更新的操作 Map params = new HashMap<>(); params.put("num",listBean.getNum()+1+""); params.put("uid","4575"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(checked ? 1:0)); params.put("num", String.valueOf(listBean.getNum())); RetrofitUtil.updatacards(params, new retrofit2.Callback() { @Override public void onResponse(retrofit2.Call call, retrofit2.Response response) { if (response.isSuccessful()){ index = index +1; if (index < childitemListSize){updateAllChild(allList,checked); }else { //查询购物车 getCartPresenter.getNetWrok(); } } }@Override public void onFailure(retrofit2.Call call, Throwable t) { } }); }//viewHolder private class GroupHolder{ CheckBox check_group; TextView text_group; }private class ChildHolder{ CheckBox check_child; SimpleDraweeView simpleDraweeView; LinearLayout linearLayout; LinearLayout addjian; TextView text_datermine; TextView text_bianji; TextView text_title; TextView text_price; TextView text_jian; TextView text_num; TextView text_add; TextView text_child_shuliang; }

一级列表布局

二级列表布局

RetrofitUtil工具类 【安卓开发|购物车操作增删改查】
import com.luobing.jinjieweek2.model.bean.AddBean; import com.luobing.jinjieweek2.model.bean.DelCardBean; import com.luobing.jinjieweek2.model.bean.QueryBean; import com.luobing.jinjieweek2.model.bean.UpdataBean; import java.util.HashMap; import java.util.Map; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; //import retrofit.GsonConverterFactory; //import retrofit.Retrofit; /** * Created by Administrator on 2018/1/6. */public class RetrofitUtil {privatestatic Retrofit retrofit = null; private RetrofitUtil() {}public static Retrofit getInstance(){ OkHttpClient instance = OkhttpUtil.getInstance(); if (retrofit==null){ synchronized (RetrofitUtil.class){ retrofit = new Retrofit.Builder() .baseUrl(Api.URR_BASE) .client(OkhttpUtil.getInstance()) .addConverterFactory(GsonConverterFactory.create()) .build(); } } return retrofit; }interface ServerInterface {@FormUrlEncoded @POST("product/getCarts") Call queryCarts(@FieldMap Map par); @FormUrlEncoded @POST("product/addCart") Call addCarts(@FieldMap Map par); @FormUrlEncoded @POST("product/updateCarts") Call updataCarts(@FieldMap Map par); @FormUrlEncoded @POST("product/deleteCart") Call delCarts(@FieldMap Map par); }/** * 参数化声明 * sellerid string 是 商户id *pid string 是 商品id *num string 是 商品数量 *selected string 是 是否选中 * @param uid * @param callback *//** * 查询购物车的方法 */public static void quertCarts(Map map,Callback callback) {Call cartsBeanCall = getInstance().create(ServerInterface.class).queryCarts(map); cartsBeanCall.enqueue(callback); }//添加购物车的方法 public static void addcards(String pid,Map map,Callback callback){//执行添加的方法 Call addBeanCall = getInstance().create(ServerInterface.class).addCarts(map); addBeanCall.enqueue(callback); }//更新购物车的方法 public static void updatacards(Map map,Callback callback){//执行添加的方法 Call updataBeanCall = getInstance().create(ServerInterface.class).updataCarts(map); updataBeanCall.enqueue(callback); }//删除购物车的方法 public static void delcards(Map map,Callback callback){//执行添加的方法 Call delCardBeanCall = getInstance().create(ServerInterface.class).delCarts(map); delCardBeanCall.enqueue(callback); }


okhttputil工具
import android.os.Environment; import android.util.Log; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by Administrator on 2018/1/6. */public class OkhttpUtil { public static final int CONNECTTIME = 0b1010; //私有静态成员变量,私有构造方法 private static OkHttpClient okHttpClient=null; private OkhttpUtil() { }public static OkHttpClient getInstance(){ if (okHttpClient==null){ synchronized (OkhttpUtil.class){ //指定缓存路径 File file = new File(Environment.getExternalStorageDirectory() , "chche"); //指定缓存大小 int chchesize = 10*1024*1024; okHttpClient = new OkHttpClient.Builder() .readTimeout(CONNECTTIME, TimeUnit.SECONDS)//读取超时 .connectTimeout(CONNECTTIME,TimeUnit.SECONDS) .writeTimeout(CONNECTTIME,TimeUnit.SECONDS) .cache(new Cache(file.getAbsoluteFile(),chchesize)) .build(); } } return okHttpClient; }/** * get请求 * 参数1 url * 参数2 回调Callback */public static void doGet(String url, Callback callback) {//创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //创建Request Request request = new Request.Builder().url(url).build(); //得到Call对象 Call call = okHttpClient.newCall(request); //执行异步请求 call.enqueue(callback); }



    推荐阅读