Skip to content Skip to sidebar Skip to footer

Read Rss Feed - Android

I'm trying to develop a simple application that reads rss feeds from a certain URL and then displays the results in a list view. Here is my rss reader, which is the main thing in t

Solution 1:

use SAXParser

public class RssParseHandler extends DefaultHandler {

private List<RssItem> rssItems;

private RssItem currentItem;

private boolean parsingTitle;

private boolean parsingLink;

public RssParseHandler() {
    rssItems = new ArrayList<RssItem>();
}

public List<RssItem> getItems() {
    return rssItems;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if ("item".equals(qName)) {
        currentItem = new RssItem();
    } else if ("title".equals(qName)) {
        parsingTitle = true;
    } else if ("link".equals(qName)) {
        parsingLink = true;
    }
}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    if ("item".equals(qName)) {
        rssItems.add(currentItem);
        currentItem = null;
    }else if ("title".equals(qName)) {
        parsingTitle = false;
    }else if ("link".equals(qName)) {
        parsingLink = false;
    }
}

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
    if (parsingTitle) {
        if (currentItem != null)
            currentItem.setTitle(new String(ch, start, length));
    }else if (parsingLink) {
        if (currentItem != null) {
            currentItem.setLink(new String(ch, start, length));
            parsingLink = false;
        }
    }
}
}
public class RssItem {

// item title
private String title;
// item link
private String link;

private String id;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getLink() {
    return link;
}

public void setLink(String link) {
    this.link = link;
}


@Override
public String toString() {
    return title;
}

}

Post a Comment for "Read Rss Feed - Android"