简易RSS阅读器---用XmlPullParser 解析器解析网络新闻

来源:互联网 发布:图片重叠软件 编辑:程序博客网 时间:2024/05/13 04:18

功能实现:

  用XmlPullParser 解析器解析网络新闻的xml文件,网络新闻总是更新,将解析的新闻列表显示在Android虚拟机上,点击其中一个新闻项显示新闻详细信息。

 

解析文件地址:http://blog.sina.com.cn/rss/1267454277.xml

实现效果:


点击其中一个显示视图

 

注意问题及知识点:

     1:访问网络需配置AndroidManifest.xml文件中的用户权限

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


    2 :将xml文件布局成列表项视图        

    3:列表视图的适配器设置

             (1)继承listActivity   利用setListAdapter()绑定适配器

         (2)  在主页布局文件布局ListView组件,setAdapter()绑定

    4:XmlPullParser解析器的使用

 

实现代码:

布局文件:首页视图含有一个列表

 

1
2
3
4
5
6
7
8
9
10
11
12
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >
                                                                                             
     <ListView
         android:id="@+id/listview"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:padding="@dimen/padding_medium"
         tools:context=".MainActivity" />
 </RelativeLayout>

 

点击其中一个新闻标题进入一个新的视图activity_show_item.xml

显示详细内容

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >
                                                                                      
     <TextView
         android:id="@+id/content"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_weight="1.0"
         android:autoLink="all"
         android:text="" />
                                                                                      
     <Button
         android:id="@+id/back"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="返回" />
                                                                                      
 </LinearLayout>

 

创建新闻实体:RSSItem

 

1
2
3
4
5
6
7
8
public class RSSItem {
                                                                                
    private String title;// 标题
    private String description;// 描述
    private String link;// 链接
    private Sring pubdate;// 出版时间
    //getters and setters 方法
 }

 

创建解析器NewsService 返回显示的新闻列表

                   (XmlPullParser 解析器解析xml文件)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class NewsService {
    public List<RSSItem> getNews(InputStream is) {
        RSSItem i = null;
        List<RSSItem> list = null;
        XmlPullParserFactory factory;
        try {
    factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser;
            parser = factory.newPullParser();
            parser.setInput(is, "UTF-8");
       int eventType = parser.getEventType();//产生第一个事件
       while (eventType != XmlPullParser.END_DOCUMENT) {// 只要不是文档结束
           String name = parser.getName();// 获取解析器当前指向的元素名称
           switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    list = new ArrayList<RSSItem>();
                    break;
                case XmlPullParser.START_TAG:
                    if ("item".equals(name)) {
                        i = new RSSItem();
                    }
                    if (i != null) {
                        if ("title".equals(name)) {
                            i.setTitle(parser.nextText());
                        }
                        if ("link".equals(name)) {
                            i.setLink(parser.nextText());
                        }
                                                                           
                        if ("pubDate".equals(name)) {
                                                                           
                            i.setPubdate(parser.nextText());
                                                                           
                        }
                        if ("description".equals(name)) {
                           i.setDescription(parser.nextText());
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                                                                           
                    if ("item".equals(name)) {
                        list.add(i);
                        i = null;
                    }
                                                                           
                }
                eventType = parser.next();// 进入下一个元素
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
 }

 

MainActivity.java代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
public class MainActivity extends Activity {
                     
     public final String RSS_URL = "http://blog.sina.com.cn/rss/1267454277.xml";
                     
     // 从网络获取RSS地址
                     
     private List<RSSItem> newslist = null;
                     
     private ListView itemlist;
                     
     @Override
                     
     public void onCreate(Bundle savedInstanceState) {
                     
         super.onCreate(savedInstanceState);
                     
         setContentView(R.layout.activity_main);
                     
         itemlist = (ListView) this.findViewById(R.id.listview);
                     
         NewsService service=new NewsService();
                     
         URL url;
                     
         try {
                     
             //使用网络上提供的xml文件进行解析
                     
             url = new URL(RSS_URL);
                     
             //得到解析的集合
                     
             newslist = service.getNews(url.openStream());
                     
         } catch (IOException e) {
                     
             e.printStackTrace();
                     
         }
                     
         showListView(); // 把rss内容绑定到ui界面进行显示
                     
     }
                     
                             
                     
  //显示新闻列表在ui界面
                     
     private void showListView() {
                     
         if (newslist == null) {
                     
             setTitle("访问的RSS无效");
                     
             return;
                     
         }
                     
         List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
                     
         int size = newslist.size();
                     
         for (RSSItem i:newslist) {
                     
             HashMap<String, Object> item = new HashMap<String, Object>();
                     
             item.put("title", i.getTitle());
                     
             item.put("date", i.getPubdate());
                     
             data.add(item);
                     
         }
                     
         //创建列表样式及显示内容的适配器
                     
         SimpleAdapter adapter = new SimpleAdapter(this, data,android.R.layout.simple_list_item_2, new String[] { "title" "date" }, new int[] { android.R.id.text1,
                     
                         android.R.id.text2 });
                     
         // listview绑定适配器
                     
         itemlist.setAdapter(adapter);
                     
                                    
                     
         itemlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                     
             // 设置itemclick事件代理
                     
             @Override
                     
             public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
                     
           Intent intent = new Intent(MainActivity.this,
                     
                         ShowItemActivity.class);// 构建一个“意图”,用于指向activity
                     
             Bundle b = new Bundle(); // 构建buddle,将要传递参数都放入buddle
                     
      b.putString("title", newslist.get(position).getTitle());       b.putString("description", newslist.get(position)
                     
                         .getDescription());
                     
     b.putString("link", newslist.get(position).getLink());            b.putString("pubdate", newslist.get(position).getPubdate());
                     
            intent.putExtras(b);
                     
            startActivity(intent);
                     
             }
                     
                             
                     
         });
                     
         itemlist.setSelection(0);
                             
     }
 }

 

创建显示详细内容Activity

ShowItemActivity.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class ShowItemActivity extends Activity {
            
     private TextView textView;
            
     private Button backbutton;
            
     @Override
            
     public void onCreate(Bundle savedInstanceState) {
            
         super.onCreate(savedInstanceState);
            
         setContentView(R.layout.activity_show_item);
            
         String content = null;
            
         Intent intent = getIntent();
            
         if (intent != null) {
            
      Bundle bundle = intent
            
                  .getExtras();
            
             if (bundle == null) {
            
                 content = "不好意思程序出错啦";
            
             } else {
            
                content = bundle.getString("title") + "\n\n"
            
            + bundle.getString("pubdate") + "\n\n"                 +bundle.getString("description").replace('\n', ' ')
            
  + "\n\n详细信息请访问以下网址:\n" + bundle.getString("link");
            
             }
            
         } else {
            
             content = "不好意思程序出错啦";
            
         }
            
         textView = (TextView) findViewById(R.id.content);
            
         textView.setText(content);
                
            
         backbutton = (Button) findViewById(R.id.back);
            
         backbutton.setOnClickListener(new      Button.OnClickListener() {
            
             public void onClick(View v) {
            
                 finish();
            
             }
            
         });
            
     }
            
  }