Android day_08 (新闻客户端案例)

案例思路

本案例要求从服务区获取数据显示在ListView控件上。

1.冲服务器获取数据,返回一个xlm文件,解析xml文件将其中内容显示在ListView上

2.重点难点:从服务器获取数据时需要网络,主线程不允许访问网络需要开辟子线程子线程中又不允许更新UI又需要跳回主线程。

如何从数据库获取xml文件,xml的解析,如何把布局文件转换成一个View。

3.使用到的知识点:

HttpURLConnection   runOnUiThread   inflate   XmlPullParser

4.代码

public class MainActivity extends AppCompatActivity {
    List<Sms> newslists;
    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //[1]找到控件
        lv = findViewById(R.id.lv);
        //准备 ListView 显示的数据
        initListData();
    }

    private void initListData() {
        new Thread() {
            public void run() {
                try {
                    //[2.1] 获取指定路径
                    String path = "http://192.168.3.138:8080/ddd.xml";
                    //[2.2] 获取URL对象
                    URL url = new URL(path);
                    //[2.3]获取HttpURLConnection对象
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //[2.4]设置请求的方式
                    conn.setRequestMethod("GET");
                    //[2.5]设置超时时间
                    conn.setConnectTimeout(5000);
                    //[2.6]获取服务器返回的状态码
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        //[2.7]获取数据  以流的形式返还
                        InputStream in = conn.getInputStream();
                        //[2.8] 创建解析xml的工具类  并调用
                        newslists = Xml.parserXml(in);
                        //使用runOnUiThread在主线程中更新UI
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                lv.setAdapter(new MyAdapter());
                            }
                        });
                        in.close();
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        }.start();
    }

    //
    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return newslists.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View v;
            if (view == null) {
                v = View.inflate(getApplicationContext(), R.layout.ietm, null);
            } else {
                v = view;
            }
            //找到控件  显示集合里的数据
            final ImageView iv_icun = v.findViewById(R.id.iv_icon);
            TextView tv_title = v.findViewById(R.id.tv_title);
            TextView tv_desc = v.findViewById(R.id.tv_desc);
            TextView tv_type = v.findViewById(R.id.tv_type);
            final int ii = i;
            new Thread() {
                @Override
                public void run() {
                    try {
                        //[2.1] 获取指定路径
                        String path = newslists.get(ii).getImage();
                        //[2.2] 获取URL对象
                        URL url = new URL(path);
                        //[2.3]获取HttpURLConnection对象
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        //[2.4]设置请求的方式
                        conn.setRequestMethod("GET");
                        //[2.5]设置超时时间
                        conn.setConnectTimeout(5000);
                        //[2.6]获取服务器返回的状态码
                        int code = conn.getResponseCode();
                        if (code == 200) {
                            //[2.7]获取数据  以流的形式返还
                            InputStream in = conn.getInputStream();
                            //[2.8] 获取图片
                            final Bitmap bitmap = BitmapFactory.decodeStream(in);
                            iv_icun.setImageBitmap(bitmap);
                            in.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            tv_title.setText(newslists.get(i).getAddress());
            tv_desc.setText(newslists.get(i).getBodyu());
            String typee = newslists.get(i).getType();
            int type = Integer.parseInt(typee);
            switch (type) {
                case 1:
                    tv_type.setText("跟帖");
                    break;
                case 2:
                    tv_type.setText("国内");
                    break;
                case 3:
                    tv_type.setText("国外");
                    break;
            }
            return v;
        }
    }

}

xml工具类代码

public class Xml {
    public static List<Sms> parserXml(InputStream in) throws Exception {
        //[0]声明集合对象
        List<Sms> weatherlists = null;
        Sms sms = null;
        //[1]获取XmlPullParser  解析实例 通过工具类Xml的Xml.newPullParser()方法
        XmlPullParser parser = android.util.Xml.newPullParser();
        //[2]设置XmlPullParser 的参数  第一个为一个流  第二个为编码方式
        parser.setInput(in, "utf-8");
        //[3]获取事件类型  不等于结尾继续向下解析
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG://解析开始标签
                    //具体判断  是哪个开始标签
                    if ("smss".equals(parser.getName())) {
                        weatherlists = new ArrayList<Sms>();
                    } else if ("sms".equals(parser.getName())) {
                        //取出这个标签的属性  0代表取第一个
                        //parser.getAttributeValue(0);
                        sms = new Sms();
                    } else if ("address".equals(parser.getName())) {
                        //取出两个标签中的数据
                        String adderss = parser.nextText();
                        sms.setAddress(adderss);
                    } else if ("bodyu".equals(parser.getName())) {
                        String bodyu = parser.nextText();
                        sms.setBodyu(bodyu);
                    } else if ("image".equals(parser.getName())) {
                        String image = parser.nextText();
                        sms.setImage(image);
                    } else if ("type".equals(parser.getName())) {
                        String type1 = parser.nextText();
                        sms.setType(type1);
                    }
                    if ("date".equals(parser.getName())) {
                        String date = parser.nextText();
                        sms.setDate(date);
                    }
                    break;
                case XmlPullParser.END_TAG://解析结束标签
                    if ("sms".equals(parser.getName())) {
                        //把数据  存入集合
                        weatherlists.add(sms);
                    }
                    break;
            }
            //不停向下解析 直到结束
            type = parser.next();
        }
        return weatherlists;
    }
}

猜你喜欢

转载自blog.csdn.net/Depths_t/article/details/81219136