当前位置: 首页 > 工具软件 > retrofit-cjs > 使用案例 >

Retrofit+Rxjava请求网络实现_购物车

柯琛
2023-12-01

Mvp_view

     void  success(int type,String data);
     void  fail(int type,String error);

Mvp_model


    interface CallBackListEner{

         void  success(int type,String data);
         void  fail(int type,String error);

    }

       void  shopcasr(int type, String url,CallBackListEner listEner);

Mvp_ModelIml

 @Override
    public void shopcasr(final int type, String url, final CallBackListEner listEner) {

           new HttpUtlis().get(url).resont(new ListEner() {
               @Override
               public void success(String data) {

                   listEner.success(type,data);
               }

               @Override
               public void fail(String error) {
                   listEner.fail(type,error);
               }
           });
    }

Mvp_presenter

 void   shopcasr(int type, String url);

Mvp_presenterIml


      MainModel mainModel;
      MainView mainView;
    public  MainPresenterIml(MainModel mainModel, MainView mainView){

         this.mainModel = mainModel;
         this.mainView = mainView;
    }

    @Override
    public void shopcasr(int type, String url) {

        mainModel.shopcasr(type,url,this);

    }

    @Override
    public void success(int type, String data) {

         mainView.success(type,data);
    }

    @Override
    public void fail(int type, String error) {

         mainView.fail(type,error);
    }

net_HttpUtlis


     String baseurl = "http://172.17.8.100";

    public HttpUtlis  get(String url){



        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseurl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();



        HttpService service = retrofit.create(HttpService.class);

        service.get(url)

                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {

                        try {
                            String data  = responseBody.string();
                            listEner.success(data);

                        } catch (IOException e) {

                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        String error = e.getMessage();
                        listEner.fail(error);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

        return  this;
    }

     ListEner listEner;
     public  void  resont(ListEner listEner){
        this.listEner = listEner;
     }

net_HttpService

 @GET
    Observable<ResponseBody> get(@Url String url);

net_ListEner


     void  success(String data);
     void  fail(String error);

MainActivity

  private RecyclerView recyle;
    private MainPresenterIml mainPresenterIml;
    private ShopCarAdapter adapter;
    private CheckBox checkbox;
    private List<ShopCarBean.DataBean> beans = new ArrayList<>();
    private TextView jiesuan,zongjia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyle = (RecyclerView)findViewById(R.id.recyle);
        jiesuan =  (TextView)findViewById(R.id.jiesuan);
        zongjia =  (TextView)findViewById(R.id.zongjia);
        checkbox = (CheckBox)findViewById(R.id.checkbox);
        checkbox.setOnClickListener(this);


        adapter = new ShopCarAdapter(MainActivity.this);
        recyle.setAdapter(adapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyle.setLayoutManager(linearLayoutManager);
        mainPresenterIml = new MainPresenterIml(new MainModelIml(),this);
        mainPresenterIml.shopcasr(0,"/ks/product/getCarts?uid=51");


        //

        adapter.resonterListListEner(new ShopCarAdapter.ChanListListEner() {
            @Override
            public void changlist(List<ShopCarBean.DataBean> list) {

                int shopCarNum=0;
                float zj = 0;
                int js = 0;

                for (int i = 0; i <list.size() ; i++) {

                    if(list.get(i).isChecked()){

                        shopCarNum++;
                    }

                    List<ShopCarBean.DataBean.ListBean> list1 = list.get(i).getList();

                    for (int j = 0; j <list1.size() ; j++){

                         if(list1.get(j).isChecked()){

                             int num = list1.get(j).getNum();
                             float price = list1.get(j).getPrice();
                             zj = zj+(price*num);
                             js = js + num;

                         }

                    }
              }

                if(shopCarNum==list.size()){//所有的商家选中
                    checkbox.setChecked(true);
                }else{
                   checkbox.setChecked(false);
                }

                //设置
                zongjia.setText(zj+"¥");
                jiesuan.setText("去结算("+js+")");
            }
        });

    }

    @Override
    public void success(int type, String data) {

        if(type == 0){

            ShopCarBean shopCarBean = new Gson().fromJson(data, ShopCarBean.class);
            beans = shopCarBean.getData();
            beans.remove(0);
            adapter.setList(beans);

        }

    }

    @Override
    public void fail(int type, String error) {

    }

    //  点击事件
    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.checkbox:// 全选的点击事件

                boolean checked = checkbox.isChecked();// 获取选中的状态
                float zj = 0;
                int js = 0;
                     for (int i = 0; i <beans.size() ; i++) {

                         beans.get(i).setChecked(checked);
                         List<ShopCarBean.DataBean.ListBean> list = beans.get(i).getList();
                          for(int j = 0; j <list.size();j++){

                              list.get(j).setChecked(checked);
                              int num = list.get(j).getNum();
                              float price = list.get(j).getPrice();
                              zj = zj+(price*num);
                              js = js + num;

                          }
                     }


                     if(!checked){

                         zj = 0.0f;
                         js = 0;
                     }

                     zongjia.setText(zj+"¥");
                     jiesuan.setText("去结算("+js+")");
                     adapter.setList(beans);
                     break;

        }
    }

MainActivity_layout

 <android.support.v7.widget.RecyclerView
        android:id="@+id/recyle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/aa">
    </android.support.v7.widget.RecyclerView>

    <RelativeLayout
        android:id="@+id/aa"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"/>


        <TextView
            android:id="@+id/zongjia"
            android:textColor="#d43c3c"
            android:textSize="18dp"
            android:text="0.0¥"
            android:layout_toRightOf="@+id/checkbox"
            android:layout_centerVertical="true"
            android:layout_marginLeft="50dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


        <RelativeLayout
            android:layout_alignParentRight="true"
            android:background="#d43c3c"
            android:layout_width="120dp"
            android:layout_height="match_parent">


            <TextView
                android:id="@+id/jiesuan"
                android:text="去结算(0)"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:textColor="#FFFFFF"
                android:textSize="15dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </RelativeLayout>

    </RelativeLayout>

ShopCarAdapter

  private List<ShopCarBean.DataBean> list = new ArrayList<>();

    private Context context;

    public ShopCarAdapter(Context context) {

         this.context = context;
    }

    @NonNull
    @Override

    public ShopCarAdapter.ShopCarViewHodel onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

         View view = View.inflate(context, R.layout.adapter,null);
         ShopCarViewHodel shopCarViewHodel = new ShopCarViewHodel(view);
         return shopCarViewHodel;
    }

    @Override
    public void onBindViewHolder(@NonNull final ShopCarAdapter.ShopCarViewHodel shopCarViewHodel, final int i) {

        shopCarViewHodel.sj.setText(list.get(i).getSellerName());
        shopCarViewHodel.check.setChecked(list.get(i).isChecked());
        List<ShopCarBean.DataBean.ListBean> listlist = list.get(i).getList();

        ShopCarLisrAdapter lisrAdapter = new ShopCarLisrAdapter(context,listlist);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        shopCarViewHodel.recyle.setLayoutManager(linearLayoutManager);
        shopCarViewHodel.recyle.setAdapter(lisrAdapter);

        shopCarViewHodel.check.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                boolean checked = shopCarViewHodel.check.isChecked();
                list.get(i).setChecked(checked);
                List<ShopCarBean.DataBean.ListBean> listchr = list.get(i).getList();

                for (int j = 0; j <listchr.size(); j++) {

                    if (checked) {

                        listchr.get(j).setChecked(true);

                    }else {

                        listchr.get(j).setChecked(false);

                    }
                }

                notifyDataSetChanged();

                chanListListEner.changlist(list);

            }
        });
    }



    private ChanListListEner chanListListEner;

    public void  resonterListListEner(ChanListListEner chanListListEner){

        this.chanListListEner = chanListListEner;
    }

    public  interface  ChanListListEner{

        void  changlist(List<ShopCarBean.DataBean> list);

    }



    @Override
    public int getItemCount() {

        return list.size();
    }

    public void setList(List<ShopCarBean.DataBean> bean) {
         this.list = bean;

         notifyDataSetChanged();
    }

    public class ShopCarViewHodel extends RecyclerView.ViewHolder {

        RecyclerView recyle;
        CheckBox check;
        TextView sj;

        public ShopCarViewHodel(@NonNull View itemView) {
            super(itemView);

            sj = (TextView)itemView.findViewById(R.id.sj);
            check = (CheckBox)itemView.findViewById(R.id.sj_check);
            recyle = (RecyclerView)itemView.findViewById(R.id.sj_recylay);

        }
    }

ShopCarLisrAdapter


    Context context;

    List<ShopCarBean.DataBean.ListBean> list;

    public ShopCarLisrAdapter(Context context, List<ShopCarBean.DataBean.ListBean> list) {
          this.context = context;
          this.list = list;

    }

    @NonNull
    @Override
    public ShopCarLisrAdapter.ShopCarViewHodel onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(context, R.layout.adapter_list,null);
        ShopCarViewHodel shopCarViewHodel = new ShopCarViewHodel(view);
        return shopCarViewHodel;
    }

    @Override
    public void onBindViewHolder(@NonNull ShopCarLisrAdapter.ShopCarViewHodel shopCarViewHodel, int i) {

           shopCarViewHodel.title.setText(list.get(i).getTitle());
           shopCarViewHodel.price.setText(list.get(i).getBargainPrice()+"¥");
           shopCarViewHodel.image.setImageURI(list.get(i).getImages());
           shopCarViewHodel.checkbox.setChecked(list.get(i).isChecked());
           int num = list.get(i).getNum();
           shopCarViewHodel.jjview.setnum(num);
    }

    @Override
    public int getItemCount() {
        return list.size();

    }

    public class ShopCarViewHodel extends RecyclerView.ViewHolder {
        JjView jjview;
        TextView title;
        TextView price;
        SimpleDraweeView image;
        CheckBox checkbox;

        public ShopCarViewHodel(@NonNull View itemView) {

            super(itemView);
            checkbox =  (CheckBox)itemView.findViewById(R.id.list_checkbox);
            image = (SimpleDraweeView)itemView.findViewById(R.id.list_image);
            price = (TextView)itemView.findViewById(R.id.list_price);
            title = (TextView)itemView.findViewById(R.id.list_title);
            jjview = (JjView)itemView.findViewById(R.id.jjview);


        }
    }

bean


    private String msg;
    private String code;
    private List<DataBean> data;
    private  boolean checked;

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    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 {
        /**
         * list : [{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"http://172.17.8.100/images/small/commodity/xbsd/sjb/5/1.jpg","images":"http://172.17.8.100/images/small/commodity/xbsd/sjb/5/1.jpg","num":2,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!","title":"一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机"},{"bargainPrice":22.9,"createtime":"2017-10-14T21:48:08","detailUrl":"http://172.17.8.100/images/small/commodity/xbsd/sjb/5/1.jpg","images":"http://172.17.8.100/images/small/commodity/xbsd/sjb/5/1.jpg","num":2,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三只松鼠零食特惠,专区满99减50,满199减100,火速抢购》","title":"三只松鼠 坚果炒货 零食奶油味 碧根果225g/袋"}]
         * sellerName : 商家1
         * sellerid : 1
         */

        private String sellerName;
        private String sellerid;
        private List<ListBean> list;
        private  boolean checked;

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }

        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 {
            /**
             * bargainPrice : 99
             * createtime : 2017-10-14T21:38:26
             * detailUrl : http://172.17.8.100/images/small/commodity/xbsd/sjb/5/1.jpg
             * images : http://172.17.8.100/images/small/commodity/xbsd/sjb/5/1.jpg
             * num : 2
             * pid : 45
             * price : 2999
             * pscid : 39
             * selected : 0
             * sellerid : 1
             * subhead : 高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!
             * title : 一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机
             */

            private float bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private float price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;
            private  boolean checked;

            public boolean isChecked() {
                return checked;
            }

            public void setChecked(boolean checked) {
                this.checked = checked;
            }

            public float getBargainPrice() {
                return bargainPrice;
            }

            public void setBargainPrice(float 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 int getPid() {
                return pid;
            }

            public void setPid(int pid) {
                this.pid = pid;
            }

            public float getPrice() {
                return price;
            }

            public void setPrice(float 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;
            }
        }
    }
注意删除空的list集合  把和价格有关的int的数据改为float 类型

App

 @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this, ImagePipelineConfig.newBuilder(App.this)
                .setMainDiskCacheConfig(
                        DiskCacheConfig.newBuilder(this)
                                //磁盘缓存路径
                                .setBaseDirectoryPath(new File(Environment.getExternalStorageDirectory().getAbsolutePath())) // 注意Android运行时权限。
                                .setMaxCacheSize(10 * 1024 * 1024)
                                .build()
                )
                .build()
        );
    }

jar

    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
 类似资料: