首页是一个轮播图以及商品的展示+bean+HttpUtils

本文详细介绍了在安卓应用中使用ViewPager与RecyclerView进行UI适配的方法,通过自定义BannerAdapter和ProductAdapter实现轮播图和商品列表的展示。同时,利用HttpUtils进行网络请求,结合Gson解析JSON数据,展示了如何在安卓应用中加载和显示动态获取的数据。

 

//BannerAdapter

public class BannerAdapter extends PagerAdapter {
    private Context context;
    private List<Banner> list;

    public BannerAdapter(Context context, List<Banner> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView img = new ImageView(context);
        Glide.with(context).load(
                StringUtils.https2Http(list.get(position).getIcon()))
                .into(img);
        container.addView(img);
        return img;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}

//ProductAdapter

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
    private Context context;
    private List<Product> list;

    public ProductAdapter(Context context, List<Product> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(context, R.layout.item_product, null);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        Product product = list.get(i);
        String[] strings = product.getImages().split("\\|");
        Glide.with(context)
                .load(StringUtils.https2Http(strings[0]))
                .into(viewHolder.imgProduct);
        viewHolder.txtTitle.setText(product.getTitle());

    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView imgProduct;
        private TextView txtTitle;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imgProduct = itemView.findViewById(R.id.img_product);
            txtTitle = itemView.findViewById(R.id.txt_title);
        }
    }
}

//INetCallBack


public interface INetCallBack {
    void success(Object obj);

    void failed(Exception e);
}


//HttpUtils

public class HttpUtils {
    private static volatile HttpUtils instance;

    private OkHttpClient client;

    private Handler handler = new Handler(Looper.getMainLooper());

    private HttpUtils() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();
    }

    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (null == instance) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }

    public void get(String url, final INetCallBack callBack, final Type type) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.failed(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Gson gson = new Gson();
                final Object o = gson.fromJson(result, type);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.success(o);
                    }
                });
            }
        });
    }
}

//StringUtils


public class StringUtils {
    public static String https2Http(String url) {
        return url.replace("https", "http");
    }
}

//Banner

public class Banner {

    /**
     * aid : 1
     * createtime : 2017-12-26T21:49:44
     * icon : https://www.zhaoapi.cn/images/quarter/ad1.png
     * productId : null
     * title : 第十三界瑞丽模特大赛
     * type : 0
     * url : http://m.mv14449315.icoc.bz/index.jsp
     */

    private int aid;
    private String createtime;
    private String icon;
    private Object productId;
    private String title;
    private int type;
    private String url;

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public String getCreatetime() {
        return createtime;
    }

    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public Object getProductId() {
        return productId;
    }

    public void setProductId(Object productId) {
        this.productId = productId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

//MessageBean

public class MessageBean<T> {
    private String msg;
    private String code;
    private T 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 T getData() {
        return data;
    }

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

//Product 

public class Product {

    /**
     * bargainPrice : 99
     * createtime : 2017-10-14T21:38:26
     * detailUrl : https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends
     * images : https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg
     * num : 11
     * 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;

    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;
    }
}

//Shopper

public class Shopper {
    private String sellerid;
    private String sellerName;
    private List<Product> list;

    public String getSellerid() {
        return sellerid;
    }

    public void setSellerid(String sellerid) {
        this.sellerid = sellerid;
    }

    public String getSellerName() {
        return sellerName;
    }

    public void setSellerName(String sellerName) {
        this.sellerName = sellerName;
    }

    public List<Product> getList() {
        return list;
    }

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

 

 

 

在 Java 开发中,`HttpUtils` 通常是一个工具类,用于简化 HTTP 请求的操作(例如 GET 和 POST 请求)。这类工具类可以封装 Apache HttpClient、OkHttp 或其他类似的库,使得发起网络请求变得更加方便直观。下面我提供一个基于 `Apache HttpClient` 实现的简单版 `HttpUtils` 示例。 --- ### HttpUtils 工具类示例 #### 引入依赖 首先需要确保项目中已经引入了 Apache HttpClient 的依赖。如果您使用的是 Maven 构建工具,请添加以下依赖项至 `pom.xml` 文件: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 如果是 Gradle,则可以在 `build.gradle` 中添加: ```groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' ``` --- #### 编写 HttpUtils 工具类 以下是完整的 `HttpUtils.java` 源码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpUtils { private static final CloseableHttpClient httpClient = HttpClients.createDefault(); /** * 发起 GET 请求 * * @param url 目标地址 * @return 响应结果字符串 */ public static String get(String url) throws Exception { HttpGet httpGet = new HttpGet(url); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { return EntityUtils.toString(response.getEntity()); } } /** * 发起 POST 请求,并携带 JSON 数据 * * @param url 目标地址 * @param json JSON 字符串参数 * @return 响应结果字符串 */ public static String post(String url, String json) throws Exception { HttpPost httpPost = new HttpPost(url); if (json != null && !json.isEmpty()) { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { return EntityUtils.toString(response.getEntity()); } } /** * 关闭客户端连接池资源(建议应用退出时调用) */ public static void shutdown() throws IOException { httpClient.close(); } } ``` --- ### 使用示例 假设我们有一个 RESTful 接口 `/api/test` 可以接收 GET 请求和 POST 请求。那么可以通过以下方式测试 `HttpUtils` 是否正常工作: ```java public class Main { public static void main(String[] args) { try { // 测试 GET 请求 String getUrl = "http://example.com/api/test"; System.out.println(HttpUtils.get(getUrl)); // 测试 POST 请求 String postUrl = "http://example.com/api/test"; String postData = "{\"key\":\"value\"}"; System.out.println(HttpUtils.post(postUrl, postData)); } catch (Exception e) { e.printStackTrace(); } finally { try { HttpUtils.shutdown(); // 确保释放资源 } catch (IOException e) { e.printStackTrace(); } } } } ``` --- ### 功能说明 1. **GET 请求** - 方法名:`get` - 参数:目标 URL 地址 - 返回值:HTTP 响应内容(String) 2. **POST 请求** - 方法名:`post` - 参数: - 第一参数为目标 URL 地址 - 第二参数为 JSON 格式的字符串数据 - 返回值:HTTP 响应内容(String) 3. **关闭资源** - 提供了一个静态方法 `shutdown()` 来手动关闭 HttpClient 连接池,避免内存泄漏问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值