admin 管理员组

文章数量: 887006

AsyncTask、Json、Spinner练习

练习题

main_activity.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    xmlns:app=""
    xmlns:tools=""
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.mrzhao.examdemo.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="点击下载"
        tools:ignore="OnClick" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Spinner>
</LinearLayout>

MainActivity:

public class MainActivity extends AppCompatActivity {private String path = ".php?stage_id=1&limit=20&page=1";
    private Spinner spinner;
    private List<String>  list  = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private MyTask myTask;


    @Override
    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner = (Spinner) findViewById(R.id.spinner);


        /**
         *  数组适配器
         *  参数1   上下文对象
         *  参数2   条目布局id
         *  参数3   数据源
         */
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, list);

        //设置适配器
        spinner.setAdapter(adapter);
        // 设置选中事件!
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {// 弹出 展示的数据
                Toast.makeText(MainActivity.this, list.get(position), Toast.LENGTH_SHORT).show();
            }@Override
            public void onNothingSelected(AdapterView<?> parent) {}});

    }/**
     * 点击下载网络数据
     *
     * @param view
     */
    public void onClick(View view) {//执行异步任务
        myTask = new MyTask();
        //执行异步任务 相当于线程的start方法
        myTask.execute();
    }@Override
    protected void onDestroy() {super.onDestroy();
        //当页面销毁的时候  取消任务
        myTask.cancel(true);

    }class MyTask extends AsyncTask<String, Void, String> {//子线程 用来下载数据
        @Override
        protected String doInBackground(String... strings) {return getDataFromNet();
        }//主线程用来更新UI
        @Override
        protected void onPostExecute(String s) {super.onPostExecute(s);
            if (!TextUtils.isEmpty(s)){//解析数据

                Gson gson = new Gson();
                FoodEntity foodEntity = gson.fromJson(s, FoodEntity.class);
                List<FoodEntity.DataBean> data = foodEntity.getData();
                for (int i = 0; i < data.size(); i++) {String title = data.get(i).getTitle();
                    list.add(title);
                }//数据更新刷新适配器
                adapter.notifyDataSetChanged();

            }}}/**
     * 从网络获取数据
     *
     * @return
     */
    private String getDataFromNet() {InputStream inputStream = null;
        ByteArrayOutputStream outputStream= null;
        try {//将 路径转换成为 URL对象
            URL url = new URL(path);
            // 使用URL打开一个链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式
            conn.setRequestMethod("GET");
            //设置链接超时
            conn.setConnectTimeout(20 * 1000);
            //设置读取超时
            conn.setReadTimeout(20 * 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;
    }}

FoodEntity:

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

本文标签: AsyncTaskJsonSpinner练习