簡易RSS閱讀器---用XmlPullParser 解析器解析網絡新聞

功能實現:

  用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();
            
             }
            
         });
            
     }
            
  }

 

發佈了29 篇原創文章 · 獲贊 6 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章