[Android] Downloading and Displaying RSS Content

RSS feeds list the latest content added to a site. The sample in this post demonstrates how to obtain RSS content and display the latest item. It will cover:

The sample code can be downloaded from the GitHub repository.


Downloading the RSS

To download RSS content, the app must first have the INTERNET permission. Declaring this in the manifest:

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

The demo activity contains only a WebView, so it may as well download the content when the activity starts:

protected void onStart() {
    super.onStart();

    // Downloading the RSS feed needs to be done on a separate thread.
    Thread downloadThread = new Thread(new Runnable() {

        public void run() {
            try {
                updateView(getLatestContent(retrieveRssDocument()));
            } catch (Exception e) {
                Log.e("Content Retriever", e.getLocalizedMessage(), e);
            }
        }
    });

    downloadThread.start();
}

Note that because obtaining data over HTTP can be slow, it must be done on a separate thread. Failure to do so may result in a NetworkOnMainThreadException (at least for API 11 anyway).

To download the content, create an URL based on the location of the RSS content and call its openConnection method and extract the content from an InputStream. Since RSS uses the XML format, the content is read into a Document:

private Document retrieveRssDocument() throws IOException,
        ParserConfigurationException, SAXException {

    URL url = new URL(source);
    URLConnection connection = url.openConnection();
    InputStream inStream = connection.getInputStream();

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        return builder.parse(new BufferedInputStream(inStream));
    } finally {
        inStream.close();
    }
}

Extract an item

RSS uses the XML format and its specification can be found on the RSS Advisory Board. Here is small sample of RSS content:

<?xml version="1.0"?>
<rss version="2.0">
   <channel>
      <title>...(Name for RSS channel)...</title>
      <link>...(Link to the site)...</link>
      <description>...(description for the channel)...</description>

      <item>
         <title>...(item title)...</title>
         <link>...(URL to the story)...</link>
         <description>...(sample content)...</description>
         <pubDate>...(when the item was published)...</pubDate>
         <guid>...(string to identify the item)...</guid>
      </item>

      ...(possibly more items)...
   </channel>
</rss>

An _item_ represents the content that has been added, such as a post, comment or article. Earlier, the content has already been read into a Document. From this, we can extract the _description_ of the first _item_:

private String getLatestContent(Document document) throws IOException,
        ParserConfigurationException, SAXException {

    NodeList nodeList = document.getElementsByTagName("item");
    int length = nodeList.getLength();
    if (length > 0) {
        return getDescriptionContent(nodeList.item(0));
    }

    return null;
}

private String getDescriptionContent(Node root) {
    if (root instanceof Element) {
        Element asElement = (Element) root;
        if (asElement.getTagName().equalsIgnoreCase("description")) {
            return asElement.getTextContent();
        }
    }

    NodeList children = root.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        String result = getDescriptionContent(node);
        if (result != null) {
            return result;
        }
    }
    return null;
}

Display the content

Finally, displaying the content is as simple as setting the content of a view! The description of the items from some RSS feeds may contain HTML. For a WebView, the content may be loaded like this:

private void updateView(final String content) {
    final WebView view = (WebView) findViewById(R.id.content);
    view.loadData("<html><body>" + content + "</body></html>",
            "text/html", null);
}
Advertisements

One Response to [Android] Downloading and Displaying RSS Content

  1. Fashion says:

    thank you for share displaying RSS Content script on my android.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: