Android - 概述

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文档包含以下元素.

Sr.No组件&描述
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指定文件.它可以是文件,也可以是Stream.在我们的例子中,它是一个stream.Its语法在下面给出 :

myparser.setInput(stream, null);


最后一步是解析XML. XML文件由事件组成,Name,Text,AttributesValue e.t.c.所以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 返回发生的事件类型.例如:文件开始,标签开始e.t.c.方法 getName 返回标签的名称,因为我们只对温度感兴趣,所以我们只检查条件语句,如果我们得到温度标签,我们调用方法 getAttributeValue 返回温度标记的值.

除了这些方法之外,此类还提供了其他方法来更好地解析XML文件.这些方法列在下面 :

Sr.NoMethod & description
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类使用的示例.它创建了一个基本的解析应用程序,允许您通过 https://www解析此处的RSS文档.tutorialspoint.com/android/sampleXML.xml 然后显示结果.

要试验这个例子,你可以在实际设备或模拟器中运行它.

步骤描述
1您将使用Android工作室来在com.example.sairamkrishna.myapplication包下创建一个Android应用程序.
2修改src/MainActivity.java文件以添加必要的代码.
3修改res/layout/activity_main以添加相应的XML组件.
4在src/HandleXML.java下创建一个新的java文件来获取和p ass XML data.
5在src/下创建一个新的java文件second.java显示XML的结果
5修改AndroidManifest.xml添加必要的互联网权限.
6运行应用程序并选择一个运行Android设备并在其上安装应用程序并验证结果.

以下是修改后的主要活动的内容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="http://IT屋.comhttps://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 .

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的文件

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("http://IT屋.comhttps://www.tutorialspoint.com/android/sampleXML.xml");
   }
}


创建一个xml文件 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 的内容修改为以下 :

<?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工作室运行应用程序,请打开项目的一个活动文件,然后单击运行Eclipse Run Icon icon从工具栏中. Android工作室在您的AVD上安装应用程序并启动它,如果您的设置和应用程序一切正常,它将显示以下模拟器窗口 :

Anroid Rss Reader教程

只需按Fetch Feed按钮即可获取RSS提要.按下后,会出现以下屏幕,显示RSS数据.

Android RSS阅读器教程

只需按结果按钮即可查看XML,该文件位于 http://it1352.comhttps://www.tutorialspoint.com/android/sampleXML.xml

Android RSS阅读器教程