异步获取数据ListView显示

来源:互联网 发布:mac能用sai吗 编辑:程序博客网 时间:2024/04/19 13:15
new MyTask().execute();
//异步获取数据显示
class MyTask extends AsyncTask<String, Void, String> {
        @Override        protected String doInBackground(String... params) {            String result = "";            try {                URL url = new URL(params[0]);                HttpURLConnection connection = (HttpURLConnection) url.openConnection();                connection.setRequestMethod("GET");                connection.setConnectTimeout(5000);                connection.setReadTimeout(5000);                if(connection.getResponseCode()==200){                    InputStream inputStream=connection.getInputStream();                    result=StreamToString.streamToStr(inputStream,"utf-8");                }            } catch (Exception e) {                e.printStackTrace();            }            return result;        }
        @Override        protected void onPostExecute(String s) {            //1.gson解析            Gson gson = new Gson();            Result result=gson.fromJson(s,Result.class);            //从对象中获取要显示的集合数据            list = result.getResults();
            //3.设置适配器            setAdapter();        }    }
    /**     * 设备适配器     */    private void setAdapter() {        if (adapter == null) {            adapter = new MyAdapter(this, list);            listView.setAdapter(adapter);        } else {            adapter.notifyDataSetChanged();        }    }
阅读全文
0 0