权限:

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

依赖:

compile 'com.google.code.gson:gson:2.8.2'

MainActivity布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.mrzhao.examdemo.MainActivity">

    <Button

android:id="@+id/getData_bt" android:onClick="onClick" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="点击获取网络数据" tools:ignore="OnClick" /> <Button android:id="@+id/toSecond_bt" android:onClick="onClick" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp"android:text="跳转到第二个页面" tools:ignore="OnClick" /> </LinearLayout>

MainActivity代码:

public class MainActivity extends AppCompatActivity {

    private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
    private FoodEntity foodEntity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.getData_bt:
                new MyTask().execute();
                break;
            case R.id.toSecond_bt:
                if (foodEntity!=null){
                    Intent intent = new Intent(this,SecondActivity.class);
                    intent.putExtra("food",foodEntity);
                    startActivity(intent);
                }
                break;
        }
    }

    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            return getDataFromNet();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //判断不是空就去解析
            if (!TextUtils.isEmpty(s)) {
                Gson gson = new Gson();
                foodEntity= gson.fromJson(s, FoodEntity.class);
            }
        }
    }
    /**
     * 网络获取数据
     *
     * @return
*/
private String getDataFromNet() {
        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(www.fengshen157.com);
        } 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; }}

SecondActivity布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.fengshen157.com schemas.android.com/apk/res/android"
    xmlns:app="http://www.huarenyl.cn   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.examdemo.SecondActivity">

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

SecondActivity代码:

public class SecondActivity extends AppCompatActivity {

    private ListView listView;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        //获取传递过来的解析对象
        FoodEntity foodEntity = (FoodEntity) getIntent().getSerializableExtra("food");
        final List<FoodEntity.DataBean> data = foodEntity.getData();

        //实例化视图
        listView = www.006665.cn  (ListView) findViewById(R.id.listView);
        myAdapter = new MyAdapter(data, this);
        listView.setAdapter(myAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(SecondActivity.this, www.huayi157.com/ data.get(position).getTitle(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Item条目布局:

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

    <TextView
        android:id="@+id/title_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="20sp"www.baohuayule.cn />
</LinearLayout>

适配器:

public class MyAdapter extends BaseAdapter {
    private List<FoodEntity.DataBean> list;
    private Context context;
    private LayoutInflater www.thylgw.cn/ 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.titleTv = (TextView) convertView.findViewById(R.id.title_tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String title = list.get(position).getTitle();
        holder.titleTv.setText(title);
        return convertView;
    }

    static class ViewHolder {
        TextView titleTv;
    }
}

解析实体类:

public class FoodEntity implements Serializable{

    /**
     * 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":"1529","food_str":"QQ糖 牛奶 芒果","num":1529},{"id":"9073","title":"家常红烧鱼","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9073.jpg","collect_num":"1419","food_str":"鲜鱼 姜 葱 蒜 花椒","num":1419},{"id":"10097","title":"家常煎豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10097.jpg","collect_num":"1406","food_str":"豆腐 新鲜红椒 青椒 葱花 油","num":1406},{"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":"1147","food_str":"大米 皮蛋 猪肉 油条 香葱","num":1147},{"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":"1004","food_str":"豆腐 木耳 胡萝卜 香葱 番茄酱","num":1004},{"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":"918","food_str":"胡萝卜 肉 蛋 生抽 盐","num":918},{"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 implements Serializable{
        /**
         * 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;
        }

ListView获取网络数据并展示优化练习的更多相关文章

  1. [置顶] 获取网络数据中的数组显示成ListView的简单流程

    首先说一下  这是我自己的个人笔记,如果想看看,不用看细节,可以看流程. 定义一个线程池 ExecutorService pool = Executors.newFixedThreadPool(15) ...

  2. Android中获取网络数据时的分页加载

    //此实在Fragment中实现的,黄色部分为自动加载,红色部分是需要注意的和手动加载,    蓝色部分是睡眠时间,自我感觉不用写  ,还有就是手动加载时,不知道为什么进去后显示的就是最后一行,求大神 ...

  3. android—获取网络数据

    取网络数据主要靠发交易(或者说请求,接口等),而这些交易由java中的网络通信,HttpURLConnection和HttpClient实现,以下是具体例子.   大家都知道,网络通信,发送请求有两种 ...

  4. Swift实战-豆瓣电台(三)获取网络数据

    观看地址:http://v.youku.com/v_show/id_XNzMwMzQxMzky.html 这节内容,我们先说了怎么将storyboard中的组件在类中进行绑定.然后写了一个类用来获取网 ...

  5. 使用NSURLSession获取网络数据和下载文件

    使用NSURLSession获取网络数据 使用NSURLSession下载文件

  6. Http方式获取网络数据

    通过以下代码可以根据网址获取网页的html数据,安卓中获取网络数据的时候会用到,而且会用Java中的sax方式解析获取到数据.(sax解析主要是解析xml)具体代码如下: package com.wy ...

  7. Swift - 异步获取网络数据封装类

    使用NSURLConnection.sendAsynchronousRequest()可以采用异步获取的方式取得数据.下面通过对数据获取类进行封装,演示如何进行数据请求与接收. 1,HttpContr ...

  8. 使用promise方式来获取网络数据

    获取网络数据 let data = []; new Promise(function(resolve,reject){ axios.post('api.php').then(function(resp ...

  9. Android架构:用消息机制获取网络数据

    网络请求,不管是什么协议,是长连接还是短连接,总是一个异步的请求,过程包括:加请求参数->发起请求->接收响应->解析数据->获得业务数据. 最挫的做法是,业务代码包揽所有这些 ...

随机推荐

  1. thinkphp发送邮箱(以thinkphp5作为示例)。

    第一步:设置我们的邮箱客户端授权码 第二步:下载相应的第三方类库(我这里用的PHPemail) 这是phpemailde 第三方类库的文件下载地址:https://github.com/PHPMail ...

  2. 构造HTTP请求Header实现“伪造来源IP”

    在阅读本文前,大家要有一个概念,在实现正常的TCP/IP 双方通信情况下,是无法伪造来源 IP 的,也就是说,在 TCP/IP 协议中,可以伪造数据包来源 IP ,但这会让发送出去的数据包有去无回,无 ...

  3. thinkphp5一些文件夹用法

    一.vendor通常放一些第三方的文件,如短信.支付宝等.用法: 1.在vendor中建一个文件夹: 2.在文件夹中新建一个类:主要命名空间(没有vendor ):如下面: 3.在控制器中调用,除了通 ...

  4. vi-vim常用命令

    vi-vim常用命令 1 简介 在UNIX系统中,创建和修改配置文件.shell脚本.初始化文件.编写程序都离不开VI. 1      vi[1]属于两个主要的UNIX规范:POSIX和单一UNIX规 ...

  5. Python基本图形绘制

    turtle的一个画布空间最小单位是像素 turtle的绘制窗体:turtle.stup(width,heigth,startx,starty) 四个参数中后两个可选 turtle空间坐标体系:tur ...

  6. sort函数

    做项目的时候,排序是一种经常要用到的操作.如果每次都自己写个冒泡之类的O(n^2)排序,不但程序容易超时,而且浪费宝贵的时间,还很有可能写错.STL里面有个sort函数,可以直接对数组排序,复杂度为n ...

  7. 「LibreOJ#515」贪心只能过样例 (暴力+bitset)

    可以发现,答案最大值只有106,于是想到用暴力维护 可以用bitset合并方案可以优化复杂度, Code #include <cstdio> #include <bitset> ...

  8. 【转】Linux系统安装Redis详细过程

    本文来源 https://blog.csdn.net/qq_20989105/article/details/76390367 ,转载前请先联系原作者并声明出处. 一.安装gcc 1.Redis在li ...

  9. Jersey2+swagger组建restful风格api及文档管理

    1.jar包引入 <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId& ...

  10. Python的入坑之路(1)

    (故事背景:由于涉及到机密的原因,暂时不方便透露,待后期再写.) 国庆长假过完之后,回来上班第二天下午,Boss跟龙哥把我叫了出去,问我要不要转人工智能.一脸懵逼的我,带着一脸懵逼听Boss说人工智能 ...