• Android Video Tutorials

Android - RSS 閱讀器



RSS 代表 Really Simple Syndication。RSS 是一種輕鬆與使用者共享網站更新和內容的方式,以便使用者無需每天訪問您的網站以獲取任何更新。

RSS 示例

RSS 是網站建立的文件,副檔名為 .xml。您可以輕鬆解析此文件並在應用程式中將其顯示給使用者。RSS 文件如下所示。

<rss version="2.0">
   <channel>
      <title>Sample RSS</title>
      <link>http://www.google.com</link>
      <description>World's best search engine</description>
   </channel>
</rss>

RSS 元素

如上所示的 RSS 文件包含以下元素。

序號 元件和描述
1

channel

此元素用於描述 RSS 提要

2

title

定義頻道的標題

3

link

定義到頻道的超連結

4

description

描述頻道

解析 RSS

解析 RSS 文件很像解析 XML。因此,現在讓我們看看如何解析 XML 文件。

為此,我們將建立 XMLPullParser 物件,但為了建立它,我們將首先建立 XmlPullParserFactory 物件,然後呼叫其 newPullParser() 方法來建立 XMLPullParser。其語法如下所示:

private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();

下一步涉及為包含 XML 的 XmlPullParser 指定檔案。它可以是檔案,也可以是流。在我們的例子中,它是一個流。其語法如下所示:

myparser.setInput(stream, null);

最後一步是解析 XML。XML 檔案由事件、名稱、文字、屬性值等組成。因此,XMLPullParser 具有用於解析 XML 檔案每個元件的單獨函式。其語法如下所示:

int event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)  {
   String name=myParser.getName();
   
   switch (event){
      case XmlPullParser.START_TAG:
      break;
      
      case XmlPullParser.END_TAG:
      if(name.equals("temperature")){
         temperature = myParser.getAttributeValue(null,"value");
      }
      break;
   }		 
   event = myParser.next(); 					
}

方法getEventType返回發生的事件型別。例如:文件開始、標籤開始等。方法getName返回標籤的名稱,由於我們只對溫度感興趣,因此我們只需在條件語句中檢查是否獲得了溫度標籤,然後呼叫方法getAttributeValue返回溫度標籤的值。

除了這些方法之外,此類還提供了其他方法來更好地解析 XML 檔案。這些方法列在下面:

序號 方法和描述
1

getAttributeCount()

此方法僅返回當前開始標籤的屬性數量。

2

getAttributeName(int index)

此方法返回由索引值指定的屬性的名稱。

3

getColumnNumber()

此方法返回當前列號,從 0 開始。

4

getDepth()

此方法返回元素的當前深度。

5

getLineNumber()

返回當前行號,從 1 開始。

6

getNamespace()

此方法返回當前元素的名稱空間 URI。

7

getPrefix()

此方法返回當前元素的字首。

8

getName()

此方法返回標籤的名稱。

9

getText()

此方法返回該特定元素的文字。

10

isWhitespace()

此方法檢查當前 TEXT 事件是否僅包含空格字元。

示例

這是一個演示 XMLPullParser 類用法的示例。它建立一個基本的解析應用程式,允許您解析此處提供的 RSS 文件/android/sampleXML.xml,然後顯示結果。

要試驗此示例,您可以在實際裝置或模擬器上執行它。

步驟 描述
1 您將使用 Android studio 在包 com.example.sairamkrishna.myapplication 下建立一個 Android 應用程式。
2 修改 src/MainActivity.java 檔案以新增必要的程式碼。
3 修改 res/layout/activity_main 以新增相應的 XML 元件。
4 在 src/HandleXML.java 下建立一個新的 java 檔案以獲取和解析 XML 資料。
5 在 src/second.java 下建立一個新的 java 檔案以顯示 XML 的結果
5 修改 AndroidManifest.xml 以新增必要的網際網路許可權。
6 執行應用程式並選擇一個正在執行的 Android 裝置,並將應用程式安裝在其上並驗證結果。

以下是修改後的主要活動檔案src/MainActivity.java的內容。

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends Activity {
   EditText title,link,description;
   Button b1,b2;
   private String finalUrl="https://tutorialspoint.tw/android/sampleXML.xml";
   private HandleXML obj;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      title = (EditText) findViewById(R.id.editText);
      link = (EditText) findViewById(R.id.editText2);
      description = (EditText) findViewById(R.id.editText3);

      b1=(Button)findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            obj = new HandleXML(finalUrl);
            obj.fetchXML();

            while(obj.parsingComplete);
            title.setText(obj.getTitle());
            link.setText(obj.getLink());
            description.setText(obj.getDescription());
         }
      });

      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent in=new Intent(MainActivity.this,second.class);
            startActivity(in);
         }
      });
   }

}

以下是 java 檔案src/HandleXML.java的內容。

package com.example.rssreader;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

public class HandleXML {
   private String title = "title";
   private String link = "link";
   private String description = "description";
   private String urlString = null;
   private XmlPullParserFactory xmlFactoryObject;
   public volatile boolean parsingComplete = true;
   
   public HandleXML(String url){
      this.urlString = url;
   }
   
   public String getTitle(){
      return title;
   }
   
   public String getLink(){
      return link;
   }
   
   public String getDescription(){
      return description;
   }
   
   public void parseXMLAndStoreIt(XmlPullParser myParser) {
      int event;
      String text=null;
      
      try {
         event = myParser.getEventType();
         
         while (event != XmlPullParser.END_DOCUMENT) {
         String name=myParser.getName();
         
         switch (event){
            case XmlPullParser.START_TAG:
            break;
            
            case XmlPullParser.TEXT:
            text = myParser.getText();
            break;
            
            case XmlPullParser.END_TAG:
            
            if(name.equals("title")){
               title = text;
            }
            
            else if(name.equals("link")){
               link = text;
            }
            
            else if(name.equals("description")){
               description = text;
            }
            
            else{
            }
            
            break;
            }
            
            event = myParser.next(); 
            }
            
            parsingComplete = false;
            }
            
            catch (Exception e) {
               e.printStackTrace();
            }
         }
         
         public void fetchXML(){
            Thread thread = new Thread(new Runnable(){
               @Override
               public void run() {
               
               try {
               URL url = new URL(urlString);
               HttpURLConnection conn = (HttpURLConnection) url.openConnection();
               
               conn.setReadTimeout(10000 /* milliseconds */);
               conn.setConnectTimeout(15000 /* milliseconds */);
               conn.setRequestMethod("GET");
               conn.setDoInput(true);
               
               // Starts the query
               conn.connect();
               InputStream stream = conn.getInputStream();
               
               xmlFactoryObject = XmlPullParserFactory.newInstance();
               XmlPullParser myparser = xmlFactoryObject.newPullParser();
               
               myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
               myparser.setInput(stream, null);
               
               parseXMLAndStoreIt(myparser);
               stream.close();
            }
            
            catch (Exception e) {
            }
         }
      });
      thread.start(); 
   }
}

建立一個檔案並將其命名為 second.java 檔案,位於目錄java/second.java

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class second extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.second_activity);
      WebView w1=(WebView)findViewById(R.id.webView);
      w1.loadUrl("https://tutorialspoint.tw/android/sampleXML.xml");
   }
}

res/layout/second_activity.xml下建立一個 xml 檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent">
   
   <WebView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/webView"
      android:layout_gravity="center_horizontal" />
</LinearLayout>

res/layout/activity_main.xml的內容修改為以下內容:

<?xml version="1.0" encoding="utf-8"?>
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="RSS example" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:layout_below="@+id/imageView"
      android:hint="Tittle"
      android:textColorHint="#ff69ff0e"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/editText"
      android:layout_alignLeft="@+id/editText"
      android:layout_alignStart="@+id/editText"
      android:textColorHint="#ff21ff11"
      android:hint="Link"
      android:layout_alignRight="@+id/editText"
      android:layout_alignEnd="@+id/editText" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText3"
      android:layout_below="@+id/editText2"
      android:layout_alignLeft="@+id/editText2"
      android:layout_alignStart="@+id/editText2"
      android:hint="Description"
      android:textColorHint="#ff33ff20"
      android:layout_alignRight="@+id/editText2"
      android:layout_alignEnd="@+id/editText2" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Fetch"
      android:id="@+id/button"
      android:layout_below="@+id/editText3"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_toLeftOf="@+id/imageView"
      android:layout_toStartOf="@+id/imageView" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Result"
      android:id="@+id/button2"
      android:layout_alignTop="@+id/button"
      android:layout_alignRight="@+id/editText3"
      android:layout_alignEnd="@+id/editText3" />

</RelativeLayout>

res/values/string.xml修改為以下內容

<resources>
   <string name="app_name">My Application</string>
</resources>

這是預設的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <uses-permission android:name="android.permission.INTERNET"/>
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
      
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
      <activity android:name=".second"></activity>
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您在進行環境設定時建立了您的AVD。要從 Android studio 執行應用程式,請開啟專案的活動檔案之一,然後單擊工具欄中的執行Eclipse Run Icon圖示。Android studio 將應用程式安裝到您的 AVD 並啟動它,如果您的設定和應用程式一切正常,它將顯示以下模擬器視窗:

Anroid Rss Reader Tutorial

只需按下“獲取提要”按鈕即可獲取 RSS 提要。按下後,將出現以下螢幕,顯示 RSS 資料。

Android RSS Reader Tutorial

只需按下結果按鈕即可檢視 XML,該 XML 位於https://tutorialspoint.tw/android/sampleXML.xml

Android RSS reader tutorial
廣告