1. 程式人生 > >OKHTTP-RecyclerView實現網路請求資料

OKHTTP-RecyclerView實現網路請求資料

build.gradle中匯入需要依賴

implementation ‘com.google.code.gson:gson:2.8.5’
implementation ‘com.android.support:design:27.1.1’
compile ‘cn.yipianfengye.android:zxing-library:1.9’
//載入圖片
implementation ‘com.github.bumptech.glide:glide:4.8.0’
annotationProcessor ‘com.github.bumptech.glide:compiler:4.8.0’

AndroidManifest.xml中加入一些許可權

 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

如果有載入圖片的工具類需要加上

例如:application中的android:name=".MyApplication"

佈局檔案使用RecyclerView展示列表

<android.support.v7.widget.RecyclerView
android:id="@+id/rv_news"
android:layout_width=“match_parent”
android:layout_gravity=“center”
android:layout_height=“wrap_content”></android.support.v7.widget.RecyclerView>

介面卡佈局,列表的樣式

<?xml version="1.0" encoding="utf-8"?>




建立一個介面類

import java.util.List;

public class News {

/**
 * msg : 請求成功
 * code : 0
 * data : [{"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","itemtype":1,"pid":45,"price":2999,"pscid":39,"salenum":4666,"sellerid":1,"subhead":"高清雙攝,就是清晰!2000+1600萬高清攝像頭,6GB大記憶體+高通驍龍835處理器,效能怪獸!","title":"一加手機5 (A5000) 6GB+64GB 月岩灰 全網通 雙卡雙待 移動聯通電信4G手機"},{"bargainPrice":6666,"createtime":"2017-10-10T16:01:31","detailUrl":"https://item.m.jd.com/product/5089273.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8284/363/1326459580/71585/6d3e8013/59b857f2N6ca75622.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9346/182/1406837243/282106/68af5b54/59b8480aNe8af7f5c.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8434/54/1359766007/56140/579509d9/59b85801Nfea207db.jpg!q70.jpg","itemtype":0,"pid":46,"price":234,"pscid":39,"salenum":868,"sellerid":2,"subhead":"【iPhone新品上市】新一代iPhone,讓智慧看起來更不一樣","title":"Apple iPhone 8 Plus (A1864) 64GB 金色 移動聯通電信4G手機"},{"bargainPrice":1599,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/1993026402.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t5863/302/8961270302/97126/41feade1/5981c81cNc1b1fbef.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7003/250/1488538438/195825/53bf31ba/5981c57eN51e95176.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5665/100/8954482513/43454/418611a9/5981c57eNd5fc97ba.jpg!q70.jpg","itemtype":2,"pid":47,"price":111,"pscid":39,"salenum":757,"sellerid":3,"subhead":"碳黑色 32GB 全網通 官方標配   1件","title":"錘子 堅果Pro 特別版 巧克力色 酒紅色 全網通 移動聯通電信4G手機 雙卡雙待 碳黑色 32GB 全網通"},{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":1,"pid":48,"price":222,"pscid":39,"salenum":656,"sellerid":4,"subhead":"【現貨新品搶購】全面屏2.0震撼來襲,驍龍835處理器,四曲面陶瓷機","title":"小米(MI) 小米MIX2 手機 黑色 全網通 (6GB+64GB)【標配版】"},{"bargainPrice":1999,"createtime":"2017-10-10T16:09:02","detailUrl":"https://item.m.jd.com/product/5025971.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t7210/232/3738666823/232298/9004583e/59c3a9a7N8de42e15.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8356/82/2107423621/109733/c019b8c6/59c3a9a6Ne9a4bdd7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t10219/74/25356012/171379/7d55e296/59c3a9a8N82fa6e02.jpg!q70.jpg","itemtype":0,"pid":49,"price":333,"pscid":39,"salenum":123,"sellerid":5,"subhead":"vivo X20 帶你開啟全面屏時代!逆光也清晰,照亮你的美!","title":"vivo X20 全面屏手機 全網通 4GB+64GB 金色 移動聯通電信4G手機 雙卡雙待"},{"bargainPrice":3455,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":2,"pid":50,"price":444,"pscid":39,"salenum":54,"sellerid":6,"subhead":"【現貨新品搶購】全面屏2.0震撼來襲,驍龍835處理器,四曲面陶瓷機","title":"小米(MI) 小米MIX2 手機 黑色 全網通 (6GB+64GB)【標配版】"},{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":1,"pid":51,"price":555,"pscid":39,"salenum":424,"sellerid":7,"subhead":"【現貨新品搶購】全面屏2.0震撼來襲,驍龍835處理器,四曲面陶瓷機","title":"小米(MI) 小米MIX2 手機 黑色 全網通 (6GB+64GB)【標配版】"},{"bargainPrice":3455,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":0,"pid":52,"price":666,"pscid":39,"salenum":212,"sellerid":8,"subhead":"【現貨新品搶購】全面屏2.0震撼來襲,驍龍835處理器,四曲面陶瓷機","title":"小米(MI) 小米MIX2 手機 黑色 全網通 (6GB+64GB)【標配版】"},{"bargainPrice":2999,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/2385655.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t2068/298/2448145915/157953/7be197df/56d51a42Nd86f1c8e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2437/128/1687178395/117431/bcc190c1/56d3fcbaNb2963d21.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2467/222/2263160610/95597/927b8a2f/56d3eafeNdecebeb6.jpg!q70.jpg","itemtype":2,"pid":53,"price":777,"pscid":39,"salenum":0,"sellerid":9,"subhead":"Super AMOLED三星雙曲面2K 屏,支援無線充電!","title":"三星 Galaxy S7 edge(G9350)4GB+32GB 鉑光金 移動聯通電信4G手機 雙卡雙待"},{"bargainPrice":3455,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":0,"pid":54,"price":888,"pscid":39,"salenum":7575,"sellerid":10,"subhead":"【現貨新品搶購】全面屏2.0震撼來襲,驍龍835處理器,四曲面陶瓷機","title":"小米(MI) 小米MIX2 手機 黑色 全網通 (6GB+64GB)【標配版】"}]
 * page : 1
 */

private String msg;
private String code;
private String page;
private List<DataBean> 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 String getPage() {
    return page;
}

public void setPage(String page) {
    this.page = page;
}

public List<DataBean> getData() {
    return data;
}

public void setData(List<DataBean> data) {
    this.data = data;
}

public static class DataBean {
    /**
     * bargainPrice : 99.0
     * 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
     * itemtype : 1
     * pid : 45
     * price : 2999.0
     * pscid : 39
     * salenum : 4666
     * sellerid : 1
     * subhead : 高清雙攝,就是清晰!2000+1600萬高清攝像頭,6GB大記憶體+高通驍龍835處理器,效能怪獸!
     * title : 一加手機5 (A5000) 6GB+64GB 月岩灰 全網通 雙卡雙待 移動聯通電信4G手機
     */

    private double bargainPrice;
    private String createtime;
    private String detailUrl;
    private String images;
    private int itemtype;
    private int pid;
    private double price;
    private int pscid;
    private int salenum;
    private int sellerid;
    private String subhead;
    private String title;

    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 getItemtype() {
        return itemtype;
    }

    public void setItemtype(int itemtype) {
        this.itemtype = itemtype;
    }

    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 getSalenum() {
        return salenum;
    }

    public void setSalenum(int salenum) {
        this.salenum = salenum;
    }

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

}

//首先介面圖片需要擷取字串,所以,這裡需要建立一個類擷取字串之後再介面卡中載入圖片處呼叫

public class ImgProcess {
public static String getImg(String images) {
String[] a = images.split("\|");
return a[0];
}
public static String setImg(String images) {
String a = images.replace(“https”,“http”);
return a;
}

}

介面卡

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;

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

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder>{
private Context context;
private List<News.DataBean> list;

public NewsAdapter(Context context) {
    this.context = context;
    list = new ArrayList<>();
}
public void setDatas(ArrayList<News.DataBean> listBeans) {
    for (int i = 0; i < listBeans.size(); i++) {
        list.add(listBeans.get(i));
    }
    notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = View.inflate(context, R.layout.rv_news, null);
    ViewHolder holder = new ViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    holder.txtTitle.setText(list.get(position).getTitle());

//因為圖片需要擷取字串,所以這裡用Glide載入圖片擷取字串,需要建立一個ImgProcess類
Glide.with(context).load(ImgProcess.getImg(list.get(position).getImages())).into(holder.imgLogo);

}

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

public class ViewHolder extends RecyclerView.ViewHolder {
    private final ImageView imgLogo;
    private final TextView txtTitle;

    public ViewHolder(View itemView) {
        super(itemView);
        imgLogo = itemView.findViewById(R.id.img_logo);
        txtTitle = itemView.findViewById(R.id.txt_title);
    }
}

}

MyApplication實現載入圖片

public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(configuration);
}
}

最後就是MainActvity中

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShowActivity extends Activity {
public static final String path=“http://120.27.23.105/product/getProducts?pscid=39&page=1”;
private RecyclerView rvNews;
private List<News.DataBean> news;
private NewsAdapter newsAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show);
    //初始化控制元件
    initView();
    news = new ArrayList<>();
    newsAdapter = new NewsAdapter(this);
    rvNews.setAdapter(newsAdapter);
    //這裡是利用網格佈局將列表分為兩列
    GridLayoutManager manager2 = new GridLayoutManager(this,2);
    rvNews.setLayoutManager(manager2);
    initDatas();
}
private void initDatas() {
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(path).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {

        private ArrayList<News.DataBean> dataBeans;

        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String strings = response.body().string();
            Gson gsons = new Gson();
            News news = gsons.fromJson(strings, News.class);
            dataBeans = (ArrayList<News.DataBean>) news.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  newsAdapter.setDatas(dataBeans);
                }
            });
        }
    });
private void initView() {
    rvNews = findViewById(R.id.rv_news);
}

}