购物车 二级列表(二)

购物车 二级列表(二) 仿淘宝购物车+请求日志(MVP抽离)

权限:

<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"/>

依赖:

implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.github.bumptech.glide:glide:4.8.0'

效果图:
在这里插入图片描述

一、main的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="购物车"
        android:textSize="16sp" />

    <ExpandableListView
        android:id="@+id/list_cart"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></ExpandableListView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <CheckBox
            android:id="@+id/check_all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:text="全选" />

        <TextView
            android:id="@+id/goods_sum_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="50dp"
            android:layout_toRightOf="@+id/check_all"
            android:text="合计:" />

    </RelativeLayout>

</LinearLayout>

二、main的具体代码
(由于我做的时候用了fragment切换 做的时候可以稍稍改改,删减一下)

package gj.com.buycar.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;


import org.w3c.dom.Text;

import java.util.List;

import gj.com.buycar.R;
import gj.com.buycar.adapter.CartAdapter;
import gj.com.buycar.bean.Goods;
import gj.com.buycar.bean.Result;
import gj.com.buycar.bean.Shop;
import gj.com.buycar.core.DataCall;
import gj.com.buycar.presenter.CartPresenter;

/**
 * 仿淘宝购物车
 */
public class Frag02 extends Fragment implements DataCall<List<Shop>>,
        CartAdapter.TotalPriceListener {


    private ExpandableListView mGoodsList;
    private CheckBox mCheckAll;
    private TextView mSumPrice;
    private CartAdapter mCartAdapter;
    private CartPresenter cartPresenter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag02,container,false);
        //初始化组件
        mGoodsList = view.findViewById(R.id.list_cart);
        mCheckAll = view.findViewById(R.id.check_all);
        mSumPrice = view.findViewById(R.id.goods_sum_price);

        //点击了全选或反选后 其他所有的商品都选中或都不选
        mCheckAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mCartAdapter.checkAll(isChecked);
            }
        });

        //设置适配器
        mCartAdapter = new CartAdapter();
        mGoodsList.setAdapter(mCartAdapter);//添加适配器
        mCartAdapter.setTotalPriceListener(this);//设置总价回调器
        mGoodsList.setGroupIndicator(null);//将默认小箭头去掉
        //让其group不能被点击
        mGoodsList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        cartPresenter = new CartPresenter(this);
        cartPresenter.requestData();
        return view;
    }

    @Override
    public void success(List<Shop> data) {
        mCartAdapter.addAll(data);
        //遍历所有group,将所有项设置成默认展开
        int groupCount = data.size();
        for (int i = 0; i <groupCount ; i++) {
            mGoodsList.expandGroup(i);
        }

        //刷新适配器
        mCartAdapter.notifyDataSetChanged();
    }

    @Override
    public void fail(Result result) {
        Toast.makeText(getActivity(), result.getCode() + "   " + result.getMsg(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void totalPrice(double totalPrice) {
        mSumPrice.setText(String.valueOf(totalPrice));//设置总价
    }
}

三、用到的适配器adapter

package gj.com.buycar.adapter;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import gj.com.buycar.R;
import gj.com.buycar.bean.Goods;
import gj.com.buycar.bean.Shop;
import gj.com.buycar.core.GJApplication;
import gj.com.buycar.view.AddSubLayout;

public class CartAdapter extends BaseExpandableListAdapter {

    //创建集合
    ArrayList<Shop> mList = new ArrayList<>();

    public CartAdapter(){

    }
    TotalPriceListener totalPriceListener;

    public void setTotalPriceListener(TotalPriceListener totalPriceListener) {
        this.totalPriceListener = totalPriceListener;
    }

    public void addAll(List<Shop> data) {
        if(data!=null){
            mList.addAll(data);
        }
    }

    //设置接口用于计算总价
    public interface TotalPriceListener{
        void totalPrice(double totalPrice);
    }

    //父级列表的数量
    @Override
    public int getGroupCount() {
        return mList.size();
    }

    //子级列表的数量
    @Override
    public int getChildrenCount(int groupPosition) {
        return mList.get(groupPosition).getList().size();
    }

    //获取父级
    @Override
    public Object getGroup(int groupPosition) {
        return mList.get(groupPosition);
    }

    //获取子级
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mList.get(groupPosition).getList().get(childPosition);
    }

    //父级id
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    //子级id
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    //父级视图
    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        GroupHolder holder = null;

        if(convertView == null){
            convertView = View.inflate(parent.getContext(),
                    R.layout.frag02_cart_group_item,null);
            holder = new GroupHolder();
            holder.checkBox = convertView.findViewById(R.id.checkBox);
            convertView.setTag(holder);
        }else {
            holder = (GroupHolder) convertView.getTag();
        }
        //获取当前的店铺
        final Shop shop = mList.get(groupPosition);

        //赋值
        holder.checkBox.setText(shop.getSellerName());//店铺名
        holder.checkBox.setChecked(shop.isCheck());//店铺前边复选框的选中状态
        holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                shop.setCheck(isChecked);//数据更新 设置选中状态
                List<Goods> goodsList = mList.get(groupPosition).getList();//得到商品信息
                //商品信息循环赋值
                for (int i = 0; i <goodsList.size() ; i++) {
                    //商铺选中则商品必须选中
                    goodsList.get(i).setSelected(isChecked?1:0);
                }
                notifyDataSetChanged();//刷新适配器
                //选中的话 计算价格
                calculatePrice();
            }
        });

        return convertView;
    }

    /**
     * 计算总价格
     */
    private void calculatePrice() {
        double totalPrice = 0;
        for (int i = 0; i <mList.size() ; i++) {//循环的是商家
            Shop shop = mList.get(i);
            for (int j = 0; j <shop.getList().size() ; j++) {//遍历商品
                Goods goods = shop.getList().get(j);
                if(goods.getSelected()==1){//如果是选中状态
                    totalPrice = totalPrice+goods.getNum()*goods.getPrice();//选中的计算总价
                }
            }
        }
        if(totalPriceListener!=null){
            totalPriceListener.totalPrice(totalPrice);//设置总价
        }
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        MyHolder holder = null;

        if(convertView == null){
            convertView = View.inflate(parent.getContext(),
                    R.layout.frag02_cart_child_item,null);
            holder = new MyHolder();
            holder.check = convertView.findViewById(R.id.cart_goods_check);
            holder.image = convertView.findViewById(R.id.image);
            holder.text = convertView.findViewById(R.id.text);
            holder.price = convertView.findViewById(R.id.text_price);
            holder.addSub = convertView.findViewById(R.id.add_sub_layout);
            convertView.setTag(holder);
        }else {
            holder = (MyHolder) convertView.getTag();
        }
        //获取商品
        final Goods goods = mList.get(groupPosition).getList().get(childPosition);
        //赋值
        holder.text.setText(goods.getTitle());
        holder.price.setText("单价:"+goods.getPrice());//单价
        //点击选中,计算价格
        holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //设置选中状态
                goods.setSelected(isChecked?1:0);
                calculatePrice();//选中计算价格
            }
        });

        if(goods.getSelected()==0){
            holder.check.setChecked(false);
        }else {
            holder.check.setChecked(true);
        }

        //设置图片
        String imageurl = "https" + goods.getImages().split("https")[1];
        Log.i("dt", "imageUrl: " + imageurl);
        imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") +
                ".jpg".length());
        Glide.with(GJApplication.getInstance()).load(imageurl).into(holder.image);//加载图片

        holder.addSub.setCount(goods.getNum());//设置商品数量
        holder.addSub.setAddSubLinstener(new AddSubLayout.AddSubLinstener() {
            @Override
            public void addSub(int count) {
                //商品设置数量
                goods.setNum(count);
                calculatePrice();//计算价格
            }
        });
        return convertView;
    }

    /**
     * 全部选中或者取消
     * @param
     * @param
     * @return
     */
    public void checkAll(boolean isCheck){
        for (int i = 0; i <mList.size() ; i++) {//循环的商家
            Shop shop = mList.get(i);//设置商家选中状态
            shop.setCheck(isCheck);
            for (int j = 0; j <shop.getList().size() ; j++) {
                Goods goods = shop.getList().get(j);//得到商品
                goods.setSelected(isCheck?1:0);//设置商品选中状态
            }
        }
        //刷新
        notifyDataSetChanged();
        calculatePrice();//调用总价
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    class GroupHolder{
        CheckBox checkBox;
    }

    class MyHolder{
        CheckBox check;
        TextView text;
        TextView price;
        ImageView image;
        AddSubLayout addSub;
    }
}

四、adapter用到的两个布局及背景

1、group布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:text="酸辣粉"/>
</LinearLayout>

2、child布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@drawable/search_edit_bg"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cart_goods_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"/>

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:minHeight="50dp"
        android:layout_toRightOf="@+id/cart_goods_check"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/text"
        android:layout_toRightOf="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="aa"
        android:padding="10dp"/>
    <TextView
        android:id="@+id/text_price"
        android:layout_toRightOf="@+id/image"
        android:layout_below="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="价格"
        android:padding="10dp"/>

    <gj.com.month_buycar.view.AddSubLayout
        android:id="@+id/add_sub_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="40dp"></gj.com.month_buycar.view.AddSubLayout>

</RelativeLayout>

背景① search_edit_bg:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!--设置圆角边框及颜色-->
    <corners android:radius="20dp"/>

    <solid
        android:color="#d8d8d8"/>

</shape>

五、适配器用到的GJApplication(记得在清单文件中注册)

application下:android:name=".core.GJApplication"

package gj.com.buycar.core;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

public class GJApplication extends Application {

    private static GJApplication instance;
    private SharedPreferences mSharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mSharedPreferences = getSharedPreferences("application",
                Context.MODE_PRIVATE);

    }

    public static GJApplication getInstance() {
        return instance;
    }

    public SharedPreferences getShare() {
        return mSharedPreferences;
    }
}

六、适配器用到的AddSubLayout

package gj.com.buycar.view;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import gj.com.buycar.R;

public class AddSubLayout extends LinearLayout implements View.OnClickListener {

    private TextView mAddBtn;
    private TextView mSubBtn;
    private TextView mNumText;

    public AddSubLayout(Context context) {
        super(context);
        initView();
    }

    public AddSubLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public AddSubLayout(Context context,AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    //创建布局视图
    private void initView() {
        //加载layout布局,第三个参数ViewGroup一定写成this
        View view = View.inflate(getContext(),
                R.layout.car_add_sub_layout,this);

        //初始化组件
        mAddBtn = view.findViewById(R.id.btn_add);
        mSubBtn = view.findViewById(R.id.btn_sub);
        mNumText = view.findViewById(R.id.text_number);

        //设置加减的点击事件
        mAddBtn.setOnClickListener(this);
        mSubBtn.setOnClickListener(this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        int width = r-1;//getWidth();
        int hright = b-t;//getHeight();
    }

    @Override
    public void onClick(View v) {
        //得到数量的值
        int number = Integer.parseInt(mNumText.getText().toString());

        switch (v.getId()){
            case R.id.btn_add:
                number++;
                mNumText.setText(number+"");//赋值
                break;

            case R.id.btn_sub:
                if(number==0){
                    Toast.makeText(getContext(),"数量不能小于0",Toast.LENGTH_LONG).show();
                    return;
                }

                number--;
                mNumText.setText(number+"");//赋值
                break;
        }
        if(addSubLinstener!=null){
            addSubLinstener.addSub(number);
        }
    }

    public void setCount(int count){
        mNumText.setText(count+"");
    }

    AddSubLinstener addSubLinstener;

    public void setAddSubLinstener(AddSubLinstener addSubLinstener) {
        this.addSubLinstener = addSubLinstener;
    }

    public  interface AddSubLinstener{
        void addSub(int count);
    }
}

七、AddSubLayout加减框用到的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--加减框-->
    <TextView
        android:id="@+id/btn_add"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/car_btn_bg"
        android:focusable="false"
        android:textSize="16sp"
        android:gravity="center"
        android:text="+"/>

    <TextView
        android:id="@+id/text_number"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:gravity="center"
        android:textSize="14sp"
        android:text="10" />

    <TextView
        android:id="@+id/btn_sub"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:textSize="16sp"
        android:focusable="false"
        android:gravity="center"
        android:background="@drawable/car_btn_bg"
        android:text="-" />

</LinearLayout>

八、加减框用到的背景设置car_btn_bg

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!--加减框的圆角边框-->
    <corners
        android:radius="5dp"></corners>

    <!--边框颜色-->
    <stroke
        android:color="@android:color/holo_red_dark"
        android:width="2dp"></stroke>

</shape>

九、接口

package gj.com.buycar.core;

import gj.com.month_buycar.bean.Result;

public interface DataCall<T> {
    void success(T data);
    void fail(Result result);
}

十、三个Bean类

①result

package gj.com.buycar.bean;

import java.util.List;

public class Result<T> {

    private int code;
    private String msg;
    private T data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

②Shop

package gj.com.buycar.bean;

import java.util.List;

import gj.com.buycar.R;

public class Shop {

        /**
         * list : []
         * sellerName :
         * sellerid : 0
         */
        //商品的bean 多写了三个东西 商品字体颜色 背景 选中状态
        private List<Goods> list;
        private String sellerName;
        private String sellerid;
        int textColor = 0xffffffff;
        int background = R.color.grayblack;

        boolean check;

        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<Goods> getList() {
            return list;
        }

        public void setList(List<Goods> list) {
            this.list = list;
        }

        public int getTextColor() {
            return textColor;
        }

        public void setTextColor(int textColor) {
            this.textColor = textColor;
        }

        public int getBackground() {
            return background;
        }

        public void setBackground(int background) {
            this.background = background;
        }

        public boolean isCheck() {
            return check;
        }

        public void setCheck(boolean check) {
            this.check = check;
        }
}

③Goods

package gj.com.buycar.bean;

import java.io.Serializable;

public class Goods implements Serializable {


    private double bargainPrice;
    private String createtime;
    private String detailUrl;
    private String images;
    private int num;
    private int pid;
    private double price;
    private int pscid;
    private int selected;
    private int sellerid;
    private String subhead;
    private String title;
    private int count = 1;//多加了一个 商品的count

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

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

    public void setPid(int 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;
    }
}

十一、model M层

package gj.com.buycar.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

import gj.com.buycar.bean.Result;
import gj.com.buycar.bean.Shop;
import gj.com.buycar.utils.HttpUtils;

public class CartModel {
    public static Result goodsList(){
        String resultString = HttpUtils.get("http://www.zhaoapi.cn/product/getCarts?uid=71");

       //try {

        //注意了
        Type type = new TypeToken<Result<List<Shop>>>(){}.getType();

        Result result = new Gson().fromJson(resultString, type);
        return result;
    /*} catch (Exception e) {

    }
    Result result = new Result();
        result.setCode(-1);
        result.setMsg("数据解析异常");
        return result;*/
    }
}

十二、presentre P层

package gj.com.buycar.presenter;

import gj.com.buycar.bean.Result;
import gj.com.buycar.core.DataCall;
import gj.com.buycar.model.CartModel;

public class CartPresenter extends BasePresenter{
    public CartPresenter(DataCall dataCall) {
        super(dataCall);
    }

    @Override
    protected Result getData(Object... args) {
        //调用网络请求获取数据M层
        Result result = CartModel.goodsList();
        return result;
    }
}

十三、BasePresenter层

package gj.com.buycar.presenter;

import android.os.Handler;
import android.os.Message;

import gj.com.buycar.bean.Result;
import gj.com.buycar.core.DataCall;

public abstract class BasePresenter {

    //接口
    DataCall dataCall;

    public BasePresenter(DataCall dataCall) {
        this.dataCall = dataCall;
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Result result = (Result) msg.obj;
            //判断是否成功
            if(result.getCode()==0){
                //将商铺信息传过去
                dataCall.success(result.getData());
            }else{
                dataCall.fail(result);
            }
        }
    };

    //得到请求数据
    public void requestData(final Object...args){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = mHandler.obtainMessage();
                message.obj = getData(args);//定义一个抽象方法调用
                mHandler.sendMessage(message);
            }
        }).start();
    }

    protected abstract Result getData(Object...args);

    //避免内存溢出
    public void unBindCall(){
        this.dataCall = null;
    }
}

十四、okHttp网络请求(根据需求 可不写)

package gj.com.buycar.utils;

import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtils {
    public static String get(String urlString){

        /**
         * 注意 日志拦截器
         */
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor())//日志拦截器
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(10,TimeUnit.SECONDS)//读取超时
                .writeTimeout(10,TimeUnit.SECONDS)//写入超时
                .build();

        Request request = new Request.Builder().url(urlString).get().build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            Log.i("dt","请求结果:"+result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String postForm(String url,String[] name,String[] value){

        OkHttpClient okHttpClient = new OkHttpClient();

        FormBody.Builder formBuild = new FormBody.Builder();
        for (int i = 0; i < name.length; i++) {
            formBuild.add(name[i],value[i]);
        }

        Request request = new Request.Builder().url(url).post(formBuild.build()).build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            String result = response.body().string();
            Log.i("dt",result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String postFile(String url,String[] name,String[] value,String fileParamName,File file){

        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if(file != null){
            // MediaType.parse() 里面是上传的文件类型。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            String filename = file.getName();
            // 参数分别为: 文件参数名 ,文件名称 , RequestBody
            requestBody.addFormDataPart(fileParamName, "jpg", body);
        }
        if (name!=null) {
            for (int i = 0; i < name.length; i++) {
                requestBody.addFormDataPart(name[i], value[i]);
            }
        }

        Request request = new Request.Builder().url(url).post(requestBody.build()).build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.code()==200) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String postJson(String url,String jsonString){

        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonString);

        Request request = new Request.Builder().url(url).post(requestBody).build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}

十五、okHttp请求日志

package gj.com.buycar.utils;

import android.util.Log;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 打印OKHTTP请求日志
 */
public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //这个chain里面包含了request和response,所以你要什么都可以从这里拿
        Request request = chain.request();

        long t1 = System.nanoTime();//请求发起的时间
        Log.i("dt",String.format("发送请求 %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();//收到响应的时间

        //这里不能直接使用response.body().string()的方式输出日志
        //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一
        //个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(1024 * 1024);

        Log.i("dt",String.format("接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
                response.request().url(),
                responseBody.string(),
                (t2 - t1) / 1e6d,
                response.headers()));

        return response;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43603817/article/details/85157981