Creating A Simple RSS Application in Android

Requirements are:
1) parse an rss feed and display the headlines in a ListView
2) when the user clicks on a headline, open the Android browser and redirect to corresponding web page.

Note: this tutorial is outdated. I would suggest you follow the new tutorial. The new tutorial is more extended, but it addresses few issues present in this example. On the other hand, if you are not looking for a very detailed tutorial and are interested only in XML parsing part, feel free to browse this example.

1. Create a new project in Eclipse:Project: SimpleRssReaderActivity: SimpleRssReaderActivity

2. Add required permissions to AndroidManifest file.
The application will make use of Internet, so this should be specified in the AndroidManifest file, otherwise an exception will be thrown. Just after the <application> tag, (as a child of <manifest> tag), add the following line:

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

3. Open the main.xml layout file, delete the already existing TextView control, and add instead a ListView with the id “list”. This should should look like this:

4. Lets create the skeleton of our main activity.
Open the SimpleRSSReaderActivity and make it extend ListActivity, instead of Activity as it comes by default. We need this in order to display the headlines in the ListView by binding to an array which will hold our data, using the list view adapter.
Add 2 instance variables: “headlines” and “links” of type List.

5. In the onCreate() method, just after the setContentView(….) , add following lines:

// Initializing instance variables
headlines = new ArrayList();
links = new ArrayList();
try {
URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);

6. In the onCreate() method we passed an input stream to setInput(): xpp.setInput(getInputStream(url), "UTF_8");getInputStream() is not a standard Java method, so we should create it. This method should take as an argument the feed url, and return the input stream.

7. Finnaly, we want when a title is clicked, the Android browser to be opened and display the corresponding article. This one is simple, we override the onListItemClick() method, get the position of article in the ListView, retrieve the coresponding link, and pass the url of that article to ACTION_VIEW intent which takes care further of displaying the web page.

Well, if everything went fine and you are done with the simple rss application, the next step to consider is how can you enhance the visual aspect of the application. Adding some style to the ListView, for example alternating between background colors, or displaying an icon next to each headline, can considerably increase the visual aspect, which will make your application look more appealing.
Take a look at this tutorial: Building a Custom Fancy ListView in Android, where I show in details how to achieve this.

This application, however, has one major drawback. Its drawback is that all the parsing and network access is done on the UI thread. As a result, you may notice that when starting the application, it “freezes” for a few seconds and then displays the headlines. To fix this issue, you should put all the parsing functionality in a background thread. In regards how to do that, you definitely should consider this post: Understanding AsyncTask – Once and Forever

I believe the errors that appear in the program are caused by the improper use of quotes.
It could be that you copied the source code, or the computer language is not english, and an improper encoding was generated when

very helpful tutorial, but i have some problem with this program, the problem is if there’s no internet connection, the program will have an error and you need to force close it, my question is, how can i program that if there’s no internet connection a dialog box will pop up and says “No internet connection” and it will go back to my Menu. can you please tell me how should i do? thanks a lot 🙂

You will need to create a new List that will store descriptions, just like we store headlines and links.
To make the headline and description appear in the same text box, most probably you will need to define a new layout file and then bind this layout file to your ListView. Take a look at this tutorial: Building a Custom Fancy ListView in Android

To make a text bold, add this property to the corresponding TextView:
android:textStyle=”bold”

That is a document with a self-closing tag,
and I suppose in this case you need to read the attributes of those tags, for example DBID, EID, and so on. Personally I did not work with files like this yet, but I saw that XMLPullParse has specific methods to work with, like: getAttributeCount();, getAttributeName(), and getAttributeValue().

However, the topic is interesting, and I’m going to explore it, and eventually writing a post.

Thanks for the great tutorials. A guide on making a simple rss reader is exactly what I’ve been looking for! I’ve got a couple of issues though:

I implemented the AsyncTask code from your other guide on this project since I’m writing for the latest version of the SDK which requires you to put all network operations like this. When I run the project it doesn’t seem to show anything. I’m not sure if the information isn’t being downloaded, or it’s not binding to the list items correctly, any ideas?

Also eclipse is complaining about using the raw type versions of List and ArrayAdapter. Should these be List and ArrayAdapter for generic types?

I have been facing few unexpected problems:
ArrayAdapter, ArrayList, IOException, MalformedURLException, URL cannot be resolved to a type
XmlPullParser cannot be resolved
XmlPullParserException cannot be resolved to a type
XmlPullParserFactory cannot be resolved
XmlPullParserFactory cannot be resolved to a type

You should import their appropriate packages.
If you are using Eclipse then go to Source -> Organize imports to automatically import all required classes. Or you may use the CTRL+SHIFT+O shortcut which does the same.

There may be many causes why it crashes, like not declaring the permissions in the AndroidManifest file.
But I suppose this is because the SimpleRssReader is trying to perform a network operation from the UI thread. In version 2.2 this was possible, but in later versions this is prohibited. You should use an AsyncTask to access the network and parse the RSS.

I’m having problems with the code in Step 7:
Multiple markers at this line
– The method onListItemClick() of type SimpleRssReaderActivity must override a superclass
method
– Syntax error on token “1”, invalid VariableDeclaratorId
– ListView cannot be resolved to a type

lange :
The method parse(String) in the type Uri is not applicable for the arguments (Object)….

any idea why?

Basically this means that Uri.parse() expects a String, but your are giving it an object of another type.
What I can say is to make sure that when parsing the RSS, you add to the List a String, it
should be like this: links.add(xpp.nextText());

Do you mind if I quote a few of your posts as long as I provide credit
and sources back to your webpage? My website is in the very same niche
as yours and my visitors would truly benefit from a lot of the information you provide here.
Please let me know if this ok with you. Cheers!

As I already stated here in comments, the tutorial was built for Android 2.2 and now is a bit outdated. Starting with Android 3.0 you are no longer allowed to perform network operations on the UI thread. If you do, you get a NetorkOnMainThreadException. You should access the RSS from an AsyncTask. That is why on 2.2 works, but on 4.0 crashes.

Not sure if I understood your question, but if you want to retrieve the URL from the XML, and then pass it to another method or class, you could put the url into a variable, and then pass that variable to the corresponding method as an argument, or to your class as an argument in constructor.

I tried to follow your tutorials but I encountered a runtime exception error that says “Your content must have a ListView who se id attribute is ‘android.R.id.list'”. I’m going nuts even if I changed the ID excactly on what the error said and felt nothing.

The tutorial is a bit outdated, starting with Android 3.0 you are no longer allowed to perform network operations on the UI thread. You should access the RSS from an AsyncTask. That is why on 2.3 works, but on 4.0 crashes.

First of all thanks for this awesome example it was indeed a gr8 help…for all those who are trying to get it run on API 17 ..all u need to do is first remove the setContentview from the oncreate() method as you will be using one of android’s inbuilt layout..then put all the content of the 5th point under the do in background method of the class extending AsyncTask … then just put the adapter code(i.e //Binding data part ) in the post execute method….lastly for the onclick listener method just modify the URi code as Uri uri = Uri.parse(String(links.get(position))); ..and dats it…..Thanx also to all the people who have replied coz I found my answers by reading through your experiences..M barely a few weeks old to this platform..and you all have been a gr8 help to me…

I have imported project well in my eclipse and also deploying on the same on my mobile HTC explorer android 2.3 but the install file when try to open i m getting error “Applcation RSSFeeder stopped un-expectedly “…plz help me to sort out this….

Thanks for such nice tutorial but I am not able to run it successfully. I could not figure out the error. I tried debug it. I found exception when it tries to set input stream for url. could you please help me. Please find the logcat as below. Thanks you in advance

You have a “NetworkOnMainThreadException” because are trying to perform network operations from the UI thread.
To fix it, that piece of code which access the network to download the rss feed should run in a separate thread.

i do the same it but lose
07-25 10:39:12.290: E/AndroidRuntime(1258): at com.example.rss.MainActivity.onCreate(MainActivity.java:43)
07-25 10:39:12.262: I/dalvikvm(1258): Turning on JNI app bug workarounds for target SDK version 10…

Reblogged this on BragitOff.com and commented:
Great Article exactly what I needed.
Anyone who owns a website/blog can create a simple app that will pull own rss feeds from the site. This way you can popularize your site on Android phones.

this error has come on it
08-04 10:10:29.870: E/dalvikvm(838): Could not find class ‘com.fasterxml.jackson.core.JsonFactory’, referenced from method org.npr.android.util.Program$ProgramFactory.downloadPrograms

Hi
i am creating a app but i need ur little help i want to give my app online support like i want to change the content like photos or text content online like news app it there any way i didn’t find proper words for that plees help sorry for confusing ques

first of all tnx for the very helpful blog,
I copied your code (i returned programming after years I havn’t done this) and i am very confused.. to my understanding, the whole code you wrote is in the main. but still, when I managed to run the application properly,I can’t even run the app it tells me äpp not installed and when I try again (from the menu) it writes “app crashed”. anyone please HELP 🙂