Android 简明教程

Android - RSS Reader

RSS 全称为 Really Simple Syndication(真正简单的联合)。RSS 是一种简单的与用户分享网站更新及内容的方式,故而用户可能无需每天都访问你的网站以了解更新信息。

RSS stands for Really Simple Syndication. RSS is an easy way to share your website updates and content with your users so that users might not have to visit your site daily for any kind of updates.

RSS Example

RSS 是一个由网站创建的扩展名为 .xml 的文档。你可以轻松地解析该文档,并将其在你的应用程序中显示给用户。RSS 文档如下所示。

RSS is a document that is created by the website with .xml extension. You can easily parse this document and show it to the user in your application. An RSS document looks like this.

<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 Elements

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

An RSS document such as above has the following elements.

Sr.No

Component & description

1

channel This element is used to describe the RSS feed

2

title Defines the title of the channel

3

link Defines the hyper link to the channel

4

description Describes the channel

Parsing RSS

解析 RSS 文档更像是解析 XML。现在让我们看看如何解析 XML 文档。

Parsing an RSS document is more like parsing XML. So now lets see how to parse an XML document.

为此,我们将创建 XMLPullParser 对象,但为了创建它,我们首先将创建 XmlPullParserFactory 对象,然后调用其 newPullParser() 方法创建 XMLPullParser。其语法如下:

For this, We will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −

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

下一步涉及为包含 XML 的 XmlPullParser 指定文件。该文件可以是文件或可以是流。在本例中,它是一个流。其语法如下所示−

The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −

myparser.setInput(stream, null);

最后一步是解析 XML。XML 文件由事件、名称、文本、属性值等组成。因此,XMLPullParser 有一个独立的功能用于解析 XML 文件的每个组件。其语法如下:

The last step is to parse the XML. An XML file consist of events , Name , Text , AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −

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

此方法返回发生的事件类型。例如:文档开始、标签开始等。该方法返回标签名称,并且因为我们仅对温度感兴趣,所以我们在条件语句中只检查是否获取了温度标签,我们调用该方法返回温度标签的值。

The method getEventType returns the type of event that happens. e.g: Document start, tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature, so we just check in conditional statement that if we got a temperature tag, we call the method getAttributeValue to return us the value of temperature tag.

除了这些方法之外,此类还提供了其他用于更好地分析 XML 文件的方法。这些方法如下所列−

Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −

Sr.No

Method & description

1

getAttributeCount() This method just Returns the number of attributes of the current start tag.

2

getAttributeName(int index) This method returns the name of the attribute specified by the index value.

3

getColumnNumber() This method returns the Returns the current column number, starting from 0.

4

getDepth() This method returns Returns the current depth of the element.

5

getLineNumber() Returns the current line number, starting from 1.

6

getNamespace() This method returns the name space URI of the current element.

7

getPrefix() This method returns the prefix of the current element.

8

getName() This method returns the name of the tag.

9

getText() This method returns the text for that particular element.

10

isWhitespace() This method checks whether the current TEXT event contains only white space characters.

Example

以下演示使用 XMLPullParser 类。它创建了一个基本解析应用程序,该应用程序允许您解析此处 /android/sampleXML.xml 中存在的 RSS 文档,然后显示结果。

Here is an example demonstrating the use of XMLPullParser class. It creates a basic Parsing application that allows you to parse an RSS document present here at /android/sampleXML.xml and then show the result.

要试验此示例,您可以在实际设备或模拟器上运行它。

To experiment with this example, you can run this on an actual device or in an emulator.

Steps

Description

1

You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add necessary code.

3

Modify the res/layout/activity_main to add respective XML components.

4

Create a new java file under src/HandleXML.java to fetch and parse XML data.

5

Create a new java file under src/second.java to display result of XML

5

Modify AndroidManifest.xml to add necessary internet permission.

6

Run the application and choose a running android device and install the application on it and verify the results.

以下是修改的主活动文件 src/MainActivity.java 的内容。

Following is the content of the modified main activity file 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://www.tutorialspoint.com/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 的内容。

Following is the content of the java file 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();
   }
}

java/second.java 下创建一个文件并将其命名为 second.java 文件

Create a file and named as second.java file under directory 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://www.tutorialspoint.com/android/sampleXML.xml");
   }
}

res/layout/second_activity.xml 创建一个 xml 文件

Create a xml file at res/layout/second_activity.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 的内容修改为以下内容:

Modify the content of res/layout/activity_main.xml to the following −

<?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 修改为以下内容

Modify the res/values/string.xml to the following

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

这是默认 AndroidManifest.xml

This is the default 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 运行应用程序,请打开项目的活动文件之一,然后单击工具栏中的运行图标。Android Studio 会在您的 AVD 上安装应用程序并启动它,如果您的设置和应用程序一切正常,它将显示以下仿真窗口 −

Let’s try to run your application. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

rss

只需按 Fetch Feed 按钮即可获取 RSS feed。按之后,将出现以下屏幕,其中将显示 RSS 数据。

Just press the Fetch Feed button to fetch RSS feed. After pressing, following screen would appear which would show the RSS data.

rss1

只需按结果按钮即可查看位于 https://www.tutorialspoint.com/android/sampleXML.xml 的 XML

Just press the result button to see XML, which is placed at https://www.tutorialspoint.com/android/sampleXML.xml

rss2