网络获取数据列表下拉刷新上拉加载更多练习

第一步首先导入PullToRefresh的包Library

布局文件:

item_layout.xml文件:

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

            android:id="@+id/food_iv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="20dp" />

            android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

                    android:id="@+id/food_name_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20sp"
            android:textSize="20sp" />

                    android:id="@+id/food_str_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20sp"
            android:textSize="20sp" />

    

main_layout.xml文件:

xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mrzhao.qbbdemo.MainActivity">

            android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


FoodEntity:

public class FoodEntity {

    /**
     * ret : 1
     * data : [{"id":"8289","title":"油焖大虾","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg","collect_num":"1659","food_str":"大虾 葱 生姜 植物油 料酒","num":1659},{"id":"2127","title":"四川回锅肉","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg","collect_num":"1585","food_str":"猪肉 青蒜 青椒 红椒 姜片","num":1585},{"id":"30630","title":"超简单芒果布丁","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg","collect_num":"1527","food_str":"QQ糖 牛奶 芒果","num":1527},{"id":"9073","title":"家常红烧鱼","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9073.jpg","collect_num":"1418","food_str":"鲜鱼 姜 葱 蒜 花椒","num":1418},{"id":"10097","title":"家常煎豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10097.jpg","collect_num":"1405","food_str":"豆腐 新鲜红椒 青椒 葱花 油","num":1405},{"id":"10509","title":"水煮肉片","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10509.jpg","collect_num":"1336","food_str":"瘦猪肉 生菜 豆瓣酱 干辣椒 花椒","num":1336},{"id":"46968","title":"红糖苹果银耳汤","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/47/46968.jpg","collect_num":"1245","food_str":"银耳 苹果 红糖","num":1245},{"id":"10191","title":"麻婆豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10191.jpg","collect_num":"1214","food_str":"豆腐 肉末 生抽 白糖 芝麻油","num":1214},{"id":"2372","title":"皮蛋瘦肉粥","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2372.jpg","collect_num":"1145","food_str":"大米 皮蛋 猪肉 油条 香葱","num":1145},{"id":"2166","title":"蚂蚁上树","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2166.jpg","collect_num":"1140","food_str":"红薯粉 肉 姜 蒜 花椒","num":1140},{"id":"2262","title":"糖醋肉","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2262.jpg","collect_num":"1074","food_str":"猪肉 红椒 黄椒 洋葱 蛋清","num":1074},{"id":"9971","title":"鱼香豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9971.jpg","collect_num":"1003","food_str":"豆腐 木耳 胡萝卜 香葱 番茄酱","num":1003},{"id":"10172","title":"干煸四季豆","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10172.jpg","collect_num":"988","food_str":"四季豆 干辣椒 蒜头 酱油 糖","num":988},{"id":"2685","title":"胡萝卜肉末蒸蛋","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2685.jpg","collect_num":"916","food_str":"胡萝卜 肉 蛋 生抽 盐","num":916},{"id":"9972","title":"虎皮青椒","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9972.jpg","collect_num":"889","food_str":"青辣椒 大蒜 香醋 白糖 生抽","num":889},{"id":"10437","title":"叉烧排骨","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10437.jpg","collect_num":"797","food_str":"排骨 李锦记叉烧酱 植物油 清水 油菜","num":797},{"id":"2892","title":"\u201c五行\u201d彩蔬汤","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2892.jpg","collect_num":"756","food_str":"黑木耳 玉米 牛蒡 胡萝卜 西兰花","num":756},{"id":"33783","title":"美人豆浆","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/34/33783.jpg","collect_num":"753","food_str":"黄豆 红豆 绿豆 黑豆 黑米","num":753},{"id":"2348","title":"麻辣肉丝面","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2348.jpg","collect_num":"753","food_str":"面条 肉丝 淀粉 酱油 辣椒","num":753},{"id":"10044","title":"土豆炖翅根","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10044.jpg","collect_num":"752","food_str":"土豆 翅根 葱 姜 料酒","num":752}]
     */

    private int ret;
    private List<DataBean> data;

    public int getRet() {
        return ret;
    }

    public void setRet(int ret) {
        this.ret = ret;
    }

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

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

    public static class DataBean {
        /**
         * id : 8289
         * title : 油焖大虾
         * pic : http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg
         * collect_num : 1659
         * food_str : 大虾 葱 生姜 植物油 料酒
         * num : 1659
         */

        private String id;
        private String title;
        private String pic;
        private String collect_num;
        private String food_str;
        private int num;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

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

        public String getPic() {
            return pic;
        }

        public void setPic(String pic) {
            this.pic = pic;
        }

        public String getCollect_num() {
            return collect_num;
        }

        public void setCollect_num(String collect_num) {
            this.collect_num = collect_num;
        }

        public String getFood_str() {
            return food_str;
        }

        public void setFood_str(String food_str) {
            this.food_str = food_str;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }
    }
}

适配器MyAdapter:

public class MyAdapter extends BaseAdapter {

    private List<FoodEntity.DataBean> list;
    private Context context;
    private LayoutInflater inflater;

    public MyAdapter(List<FoodEntity.DataBean> list, Context context) {
        this.list = list;
        this.context = context;
        //初始化布局加载器
        inflater = LayoutInflater.from(context);
    }

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

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_layout, parent, false);
            holder = new ViewHolder();
            holder.foodPicIv = (ImageView) convertView.findViewById(R.id.food_iv);
            holder.foodNameTv = (TextView) convertView.findViewById(R.id.food_name_tv);
            holder.foodStrTv = (TextView) convertView.findViewById(R.id.food_str_tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        FoodEntity.DataBean dataBean = list.get(position);
        holder.foodNameTv.setText(dataBean.getTitle());
        holder.foodStrTv.setText(dataBean.getFood_str());
        //显示图片
        Picasso.with(context).load(dataBean.getPic()).into(holder.foodPicIv);


        return convertView;
    }

    static class ViewHolder {
        ImageView foodPicIv;
        TextView foodNameTv;
        TextView foodStrTv;
    }
}


MainActivity:

public class MainActivity extends AppCompatActivity {


    private PullToRefreshListView listView;
    //想要访问的网络路径
    private String path = "";
    //定义数据源
    private List<FoodEntity.DataBean> list = new ArrayList<>();
    private MyAdapter myAdapter;
    //定义一个页码
    private int pager = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (PullToRefreshListView) findViewById(R.id.listView);
        //设置支持下拉刷新及上拉加载更多
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        //创建一个适配器
        myAdapter = new MyAdapter(list, this);
        //设置适配器
        listView.setAdapter(myAdapter);
        //添加条目点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                //点击的条目的对应数据实体
                FoodEntity.DataBean dataBean = list.get(position - 1);

                Toast.makeText(MainActivity.this, dataBean.getTitle(), Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("食物信息");
                //初始化自定义的View
                View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_layout, null);
                //实例化每个字视图
                ImageView foodIv = (ImageView) dialogView.findViewById(R.id.food_iv);
                TextView foodNameTv = (TextView) dialogView.findViewById(R.id.food_name_tv);
                TextView foodStrTv = (TextView) dialogView.findViewById(R.id.food_str_tv);
                //设置字视图应该展示的内容
                Picasso.with(MainActivity.this).load(dataBean.getPic()).into(foodIv);
                foodNameTv.setText(dataBean.getTitle());
                foodStrTv.setText(dataBean.getFood_str());

                //设置视图
                builder.setView(dialogView);
                //展示视图
                builder.show();
            }
        });
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新执行
                pager = 1;
                //清空原来的数据
                list.clear();
                //执行下载
                new MyTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉加载更多执行
                pager++;
                //执行下载
                new MyTask().execute();
            }
        });

        //获取路径
        getPathFromAssets();
        //开启下载
        new MyTask().execute();
    }


    /**
     * 获取网络数据的异步任务
     */
    class MyTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            return getJSONFromNet(path + pager);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //刷新完成
            listView.onRefreshComplete();
            if (!TextUtils.isEmpty(s)) {
                Gson gson = new Gson();
                FoodEntity foodEntity = gson.fromJson(s, FoodEntity.class);
                //获取数据中的集合
                List<FoodEntity.DataBean> data = foodEntity.getData();
                if (data != null && data.size() > 0) {
                    //更新UI
                    list.addAll(data);
                    //数据源更新后刷新适配器
                    myAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    /**
     * 网络获取json数据工具类
     *
     * @param path
     * @return
     */
    public String getJSONFromNet(String path) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(30 * 1000);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                return outputStream.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return null;
    }


    /**
     * Assets里获取 想要访问的路径
     */
    private void getPathFromAssets() {
        try {
            //获取内容的流
            InputStream inputStream = getAssets().open("path.txt");
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            ByteArrayOutputStream opt = new ByteArrayOutputStream();
            opt.write(bytes, 0, bytes.length);
            //拿到最终的结果
            path = opt.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(Android课程练习)