andriod——完美实习网络获取数据购物车

本文详细探讨了如何在Android平台上实现网络数据的获取,并将其应用于购物车功能的开发中,涵盖了网络请求、数据解析、UI展示以及购物车数据管理等关键环节。
摘要由CSDN通过智能技术生成




实现功能:全选/反选功能,计算商品数量,统计总价,实现加减按钮,实现删除功能
首先添加两个布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/main_rlv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="9"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

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

        <TextView
            android:id="@+id/cart_foot_totalPrice"
            android:layout_height="match_parent"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="#ff5000"
            android:gravity="center_vertical"
            android:paddingLeft="20dp"
            android:text="结算()"
            android:textColor="#FFF"
            android:textSize="16dp"
            android:layout_width="120dp" />

        <TextView
            android:id="@+id/cart_foot_totalCount"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@id/cart_foot_totalPrice"
            android:layout_toStartOf="@id/cart_foot_totalPrice"
            android:gravity="center_vertical"
            android:text="合计"
            android:layout_width="80dp" />
    </RelativeLayout>
</LinearLayout>
rlv.xml

<?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="match_parent"
    android:orientation="vertical">

    <CheckBox
        android:id="@+id/cart_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp" />

    <ImageView
        android:id="@+id/cart_shopIv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@id/cart_box"
        android:layout_toRightOf="@id/cart_box"
        android:padding="10dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/cart_delect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="45dp"
        android:text="删除"
        android:textSize="20sp" />


    <TextView
        android:id="@+id/cart_goodname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="商品名字"
        android:layout_above="@id/cart_shopIv"
        android:layout_alignLeft="@id/cart_shopIv"
        android:layout_alignStart="@id/cart_shopIv" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/cart_shopIv"
        android:layout_toEndOf="@id/cart_shopIv">
        <TextView
            android:id="@+id/cart_goodprice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="商品价格" />

        <LinearLayout
            android:layout_width="80dp"
            android:layout_height="20dp"
            android:layout_marginEnd="36dp"
            android:layout_marginRight="36dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/cart_jian"
                android:layout_width="20dp"
                android:layout_height="wrap_content"
                android:src="@mipmap/jian" />

            <TextView
                android:id="@+id/cart_num"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="1"
                android:textSize="20sp"
                android:layout_width="40dp" />

            <ImageView
                android:id="@+id/cart_jia"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@mipmap/jia" />
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

adapter——Rlv_Adapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.newcar.R;
import com.example.newcar.bean.CartBean;
import com.example.newcar.eventbusevent.MessageEvent;
import com.example.newcar.eventbusevent.PriceAndCountEvent;
import com.squareup.picasso.Picasso;
import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class Rlv_Adapter extends RecyclerView.Adapter<Rlv_Adapter.MyViewHodler> {
    private Context context;
    private List<CartBean.DataBean.ListBean> list;


    public Rlv_Adapter(Context context, List<CartBean.DataBean.ListBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public MyViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.rlv, null);
        return new MyViewHodler(view);
    }

    @Override
    public void onBindViewHolder(final MyViewHodler holder, final int position) {
        final CartBean.DataBean.ListBean listBean = list.get(position);
        holder.mBoxCart.setChecked(listBean.isCheck());
        holder.mGoodnameCart.setText(listBean.getTitle());
        holder.mGoodpriceCart.setText(listBean.getPrice() + "");
        holder.mNumCart.setText(listBean.getNum() + "");
        String[] split = listBean.getImages().split("\\|");
        Picasso.with(context).load(split[0]).resize(100, 100).into(holder.mShopIvCart);
        holder.mBoxCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean checked = holder.mBoxCart.isChecked();
                listBean.setCheck(checked);
                boolean checkBox = selsectAllCheckBox();
                changeAllCbState(checkBox);
                PriceAndCountEvent priceAndCountEvent = compute();
                EventBus.getDefault().post(priceAndCountEvent);
                notifyDataSetChanged();
            }
        });
        //加号的点击监听
        holder.mJiaCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //现获取当前的数量
                int num = listBean.getNum();
                //数量加1后显示在界面
                holder.mNumCart.setText(++num + "");
                //把数量存进对象
                listBean.setNum(num);
                //获取当前子条目的复选框的选中状态
                if (holder.mBoxCart.isChecked()) {
                    当前的复选框为选中状态使  改变总数和总价
                    PriceAndCountEvent priceAndCountEvent = compute();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        });
        //减号的点击监听
        holder.mJianCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取当前的数量
                int num = listBean.getNum();
                //当前的数量为1时  直接返回
                if (num == 1) {
                    return;
                }
                //改变当前的数量显示
                holder.mNumCart.setText(--num + "");
                //把当前的数量存进对象
                listBean.setNum(num);
                //获取当前子条目的复选框的选中状态
                if (holder.mBoxCart.isChecked()) {
                    当前的复选框为选中状态使  改变总数和总价
                    PriceAndCountEvent priceAndCountEvent = compute();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        });
        //子条目删除的点击监听
        holder.mDelectCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除子条目对用的数据
                list.remove(position);
                //修改总数和总价
                EventBus.getDefault().post(compute());
                //刷新适配器
                notifyDataSetChanged();
            }
        });
    }
    /**
     * 改变全选Box的状态
     */
    private void changeAllCbState(boolean flag) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setChecked(flag);
        EventBus.getDefault().post(messageEvent);
    }

    /**
     * 计算列表中,选中的钱和数量
     */
    private PriceAndCountEvent compute() {
        int count = 0;
        int price = 0;
        //遍历子条目集合
        for (int i = 0; i < list.size(); i++) {
            CartBean.DataBean.ListBean listBean = list.get(i);
            //判断当前子条目是否被选中
            if (listBean.isCheck()) {
                //选中则增加价钱和数量
                price += listBean.getNum() * listBean.getPrice();
                count += listBean.getNum();
            }
        }
        //实例化一个对象  返回
        return new PriceAndCountEvent(price, count);
    }

    /**
     * 遍历集合,查询是否全选
     */
    private boolean selsectAllCheckBox() {
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).isCheck()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 设置全选、反选
     */
    public void changeAllListCbState(boolean flag) {
        //遍历组的集合
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCheck(flag);
        }
        //返回总数量,总价钱
        EventBus.getDefault().post(compute());
        //刷新
        notifyDataSetChanged();
    }


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

    class MyViewHodler extends RecyclerView.ViewHolder {
        private CheckBox mBoxCart;
        private ImageView mShopIvCart;
        private TextView mDelectCart;
        private TextView mGoodnameCart;
        private TextView mGoodpriceCart;
        private ImageView mJianCart;
        private TextView mNumCart;
        private ImageView mJiaCart;

        public MyViewHodler(View itemView) {
            super(itemView);
            mBoxCart = itemView.findViewById(R.id.cart_box);
            mShopIvCart = itemView.findViewById(R.id.cart_shopIv);
            mDelectCart = itemView.findViewById(R.id.cart_delect);
            mGoodnameCart = itemView.findViewById(R.id.cart_goodname);
            mGoodpriceCart = itemView.findViewById(R.id.cart_goodprice);
            mJianCart = itemView.findViewById(R.id.cart_jian);
            mNumCart = itemView.findViewById(R.id.cart_num);
            mJiaCart = itemView.findViewById(R.id.cart_jia);
        }
    }
}

bean——CartBean
//http://120.27.23.105/product/getCarts?uid=71
http://120.27.23.105/product/getCarts?uid=71&source=android


eventbusevent——MessageEvent
package com.example.newcar.eventbusevent;

public class MessageEvent {
    private boolean checked;

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}
eventbusevent——PriceAndCountEvent
public class PriceAndCountEvent {
    private int price;
    private int count;

    public PriceAndCountEvent(int price, int count) {
        this.price = price;
        this.count = count;
    }

    public PriceAndCountEvent() {
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
model——IShopCart_M
import com.example.newcar.bean.CartBean;
import com.example.newcar.net.OnNetListenner;

import java.util.Map;


public interface IShopCart_M {
    void doGetCartBean(Map<String, String> map, OnNetListenner<CartBean> onNetListenner);
}

model——ShopCart_M
import com.example.newcar.bean.CartBean;
import com.example.newcar.net.API;
import com.example.newcar.net.MyOkHttpUtil;
import com.example.newcar.net.OnNetListenner;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class ShopCart_M implements IShopCart_M {
    @Override
    public void doGetCartBean(Map<String, String> map, final OnNetListenner<CartBean> onNetListenner) {
        MyOkHttpUtil.getOkHttpUtil().doPost(API.CARTS, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                 onNetListenner.doShiBai(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson=new Gson();
                CartBean cartBean = gson.fromJson(json, CartBean.class);
                onNetListenner.doChengGong(cartBean);
            }
        });
    }
}
net——API
public interface API {
    /**
     * "uid", "71"
     */
    String CARTS="http://120.27.23.105/product/getCarts";
}

net——MyOkHttpUtil
import java.io.File;
import java.util.Map;

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

public class MyOkHttpUtil {
    private static MyOkHttpUtil okHttpUtil;
    private final OkHttpClient client;

    private MyOkHttpUtil() {
        client = new OkHttpClient.Builder()
                .build();
    }

    public static MyOkHttpUtil getOkHttpUtil() {
        if (okHttpUtil == null) {
            synchronized (MyOkHttpUtil.class) {
                if (okHttpUtil == null) {
                    okHttpUtil = new MyOkHttpUtil();
                }
            }
        }
        return okHttpUtil;
    }

    public void doGet(String url, Callback callback) {
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }

    public void doPost(String url, Map<String, String> map, Callback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : map.keySet()) {
            builder.add(key, map.get(key));
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).post(body).build();
        client.newCall(request).enqueue(callback);
    }

    public void loadFile(String url, File file, String fileName, Callback callback) {
        //设置文件类型
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //设置请求体
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", fileName, requestBody)
                .build();
        //请求方式
        Request request = new Request.Builder().url(url).post(body).build();
        client.newCall(request).enqueue(callback);
    }

    public void doDown(String url,Callback callback){
        Request build = new Request.Builder().url(url).build();
        client.newCall(build).enqueue(callback);
    }


}
net——OnNetListenner
public interface OnNetListenner<T> {
    void doChengGong(T t);

    void doShiBai(Exception e);
}

presenter——presenterShopCart_P

import com.example.newcar.bean.CartBean;
import com.example.newcar.model.ShopCart_M;
import com.example.newcar.net.OnNetListenner;
import com.example.newcar.view.IShopCart_V;

import java.util.HashMap;
import java.util.Map;

public class ShopCart_P {
    private IShopCart_V shopCartV;
    private final ShopCart_M shopCartM;

    public ShopCart_P(IShopCart_V shopCartV) {
        shopCartM = new ShopCart_M();
        this.shopCartV = shopCartV;
    }

    public void doGetCartBean() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", "71");
        shopCartM.doGetCartBean(map, new OnNetListenner<CartBean>() {
            @Override
            public void doChengGong(CartBean cartBean) {
                shopCartV.setCartBean(cartBean );
            }

            @Override
            public void doShiBai(Exception e) {
                e.printStackTrace();
            }
        });
    }
}
view——IShopCart_V
import com.example.newcar.bean.CartBean;

public interface IShopCart_V {
    void setCartBean(CartBean cartBean);
}
main——
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.newcar.adapter.Rlv_Adapter;
import com.example.newcar.bean.CartBean;
import com.example.newcar.eventbusevent.MessageEvent;
import com.example.newcar.eventbusevent.PriceAndCountEvent;
import com.example.newcar.presenter.ShopCart_P;
import com.example.newcar.view.IShopCart_V;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener, IShopCart_V {

    private CheckBox mFootBoxCart;
    private TextView mFootTotalPriceCart;
    private TextView mFootTotalCountCart;
    private List<CartBean.DataBean.ListBean> list;
    private RecyclerView mRlvMain;
    private Rlv_Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
        mFootBoxCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.changeAllListCbState(mFootBoxCart.isChecked());
            }
        });
    }

    private void initView() {
        list = new ArrayList<>();
        mFootBoxCart = (CheckBox) findViewById(R.id.cart_foot_box);
        mFootBoxCart.setOnClickListener(this);
        mFootTotalPriceCart = (TextView) findViewById(R.id.cart_foot_totalPrice);
        mFootTotalCountCart = (TextView) findViewById(R.id.cart_foot_totalCount);
        mRlvMain = (RecyclerView) findViewById(R.id.main_rlv);
        mRlvMain.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        ShopCart_P shopCartP = new ShopCart_P(this);
        shopCartP.doGetCartBean();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cart_foot_box:
                // TODO 17/11/20
                break;
            default:
                break;
        }
    }

    @Override
    public void setCartBean(final CartBean cartBean) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //获取数据
                List<CartBean.DataBean> data = cartBean.getData();
                for (int i = 0; i < data.size(); i++) {
                    List<CartBean.DataBean.ListBean> listBeen = data.get(i).getList();
                    for (int j = 0; j < listBeen.size(); j++) {
                        list.add(listBeen.get(j));
                    }
                }
                adapter = new Rlv_Adapter(MainActivity.this, list);
                mRlvMain.setAdapter(adapter);
            }
        });

    }

    @Subscribe
    public void onMessageEvent(MessageEvent event) {
        mFootBoxCart.setChecked(event.isChecked());
    }

    @Subscribe
    public void onMessageEvent(PriceAndCountEvent event) {
        mFootTotalPriceCart.setText("合计¥" + event.getPrice());
        mFootTotalCountCart.setText("结算(" + event.getCount() + ")");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值