How to write Android RSS parser

Important!
If you are writing code for Android 4+ platform use this RSS Reader modification – Android AsyncTask RSS Reader. It seems that in Android 4+ all network activities needs to be encapsulated using AsyncTask (thx Duke! – comment)

In this tutorial we are going to show You how to write Android RSS parser application. Topics that we are going to talk about are: XML parsing, connecting to the network displaying data in the form of clickable list.

If You don’t have an Android Development Environment Installation see how You can easily set it up. Tutorial is available here.

We are going to begin by generating a project. To do this follow those steps:

  • Right click in the Package Explorer window
  • Select New and then Android Project
  • Enter a Project name
  • Click Next
  • Select a platform on which You are going to run Your application
  • And Click Next
  • Now enter your application package name
  • And Click Finish

Now we are going to write some code, the RssItem class. The very first class we’re going to create will be a representation of an “Item”. The “Item” is a name of a Tag containing the Element according to RSS specification which contains the article’s attributes like URLs, publish dates, topics, categories, tags etc.

RssItem.java

package com.itcuties.android.reader.data;
/**
 * This code encapsulates RSS item data.
 * Our application needs title and link data.
 *
 * @author ITCuties
 */
public class RssItem {
	// item title
	private String title;
	// item link
	private String link;
	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;
	}
}

So we’ve got the class which represents data gathered from our RSS channel. Because our data is structured as an XML document, we will use an SAX parser to be able to retrieve XML items. SAX is a stream parser. So we will create a handler which reacts on individual events, like opening and closing tags. So let’s write the next class – RssParserHandler.

RssParseHandler.java

package com.itcuties.android.reader.util;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.itcuties.android.reader.data.RssItem;
/**
 * SAX tag handler. The Class contains a list of RssItems which is being filled while the parser is working
 * @author ITCuties
 */
public class RssParseHandler extends DefaultHandler {

	// List of items parsed
	private List<RssItem> rssItems;
	// We have a local reference to an object which is constructed while parser is working on an item tag
	// Used to reference item while parsing
	private RssItem currentItem;
	// We have two indicators which are used to differentiate whether a tag title or link is being processed by the parser
	// Parsing title indicator
	private boolean parsingTitle;
	// Parsing link indicator
	private boolean parsingLink;

	public RssParseHandler() {
		rssItems = new ArrayList();
	}
	// We have an access method which returns a list of items that are read from the RSS feed. This method will be called when parsing is done.
	public List<RssItem> getItems() {
		return rssItems;
	}
	// The StartElement method creates an empty RssItem object when an item start tag is being processed. When a title or link tag are being processed appropriate indicators are set to true.
	@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;
		}
	}
	// The EndElement method adds the  current RssItem to the list when a closing item tag is processed. It sets appropriate indicators to false -  when title and link closing tags are processed
	@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;
		}
	}
	// Characters method fills current RssItem object with data when title and link tag content is being processed
	@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;
			}
		}
	}
}

Now let’s write a piece of code responsible for launching our SAX parser. This class will process the RSS stream.

RssReader.java

package com.itcuties.android.reader.util;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.itcuties.android.reader.data.RssItem;

/**
 * Class reads RSS data.
 * @author ITCuties
 */
public class RssReader {
	// Our class has an attribute which represents RSS Feed URL
	private String rssUrl;
	/**
	 * We set this URL with the constructor
	 */
	public RssReader(String rssUrl) {
		this.rssUrl = rssUrl;
	}
	/**
	 * Get RSS items. This method will be called to get the parsing process result.
	 * @return
	 */
	public List<RssItem> getItems() throws Exception {
		// At first we need to get an SAX Parser Factory object
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// Using factory we create a new SAX Parser instance
		SAXParser saxParser = factory.newSAXParser();
		// We need the SAX parser handler object
		RssParseHandler handler = new RssParseHandler();
		// We call the method parsing our RSS Feed
		saxParser.parse(rssUrl, handler);
		// The result of the parsing process is being stored in the handler object
		return handler.getItems();
	}
}

Next piece of code is going to display our RSS parsing results in the form of a clickable list. We need to write a class that implements OnItemClickListener.

ListListener.java

package com.itcuties.android.reader.listeners;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.itcuties.android.reader.data.RssItem;
/**
 * Class implements a list listener.
 * @author ITCuties
 */
public class ListListener implements OnItemClickListener {
	// Our listener will contain a reference to the list of RSS Items
	// List item's reference
	List<RssItem> listItems;
	// And a reference to a calling activity
	// Calling activity reference
	Activity activity;
	/** We will set those references in our constructor.*/
	public ListListener(List<RssItem> aListItems, Activity anActivity) {
		listItems = aListItems;
		activity  = anActivity;
	}

	/** Start a browser with url from the rss item.*/
	public void onItemClick(AdapterView parent, View view, int pos, long id) {
		// We create an Intent which is going to display data
		Intent i = new Intent(Intent.ACTION_VIEW);
		// We have to set data for our new Intent
        i.setData(Uri.parse(listItems.get(pos).getLink()));
	    // And start activity with our Intent
		activity.startActivity(i);
	}
}

Next thing to do is to add a List View to our application layout. You can achieve that by:

  • Expanding the res folder in the package explorer section and navigating to layout directory
  • Clicking on the main.xml which describes the application layout
  • Removing the default layout
  • Adding a List View from the Composite section

Next step is to put all the things together. We are going to code our activity.

ITCutiesReaderAppActivity.java

package com.itcuties.android.reader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.itcuties.android.reader.data.RssItem;
import com.itcuties.android.reader.listeners.ListListener;
import com.itcuties.android.reader.util.RssReader;

/**
 * Main application activity.
* @author ITCuties
*/
public class ITCutiesReaderAppActivity extends Activity {
	/**
	 * This method creates main application view
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set view
		setContentView(R.layout.main);
		try {
			// Create RSS reader
			RssReader rssReader = new RssReader("http://www.itcuties.com/feed/");
			// Get a ListView from main view
			ListView itcItems = (ListView) findViewById(R.id.listMainView);
			// Create a list adapter
			ArrayAdapter adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());
			// Set list adapter for the ListView
			itcItems.setAdapter(adapter);
			// Set list view item click listener
			itcItems.setOnItemClickListener(new ListListener(rssReader.getItems(), this));
		} catch (Exception e) {
			Log.e("ITCRssReader", e.getMessage());
		}
	}
}

The application code is ready, but there is one last thing to enable our application to work on the network… The right Permission settings. You will find these in the AndroidManifest.xml. Follow those steps:

  • Open AndroidManifest.xml
  • Click the Permissions tab
  • Click Add and select Uses Permissions
  • Find and select the android.permission.INTERNET permission

That’s all.

You can download all the codes in the form of Eclipse project here.

You can install this application from here.

244 Responses to "How to write Android RSS parser"

  1. sutadi says:

    Thank’s for the tutorial, very simple and help me parsing my blog’s feed. Just information, your script in the video are different with the text below it. Maybe you can fix it :)

    I have a question. for this feed, i want use custom listview where in a row there are image and textview. How i can get aech title so ican put that in a textview in my custom listview. i tried ti get RssItem.getTitle but it doesn’t work.

    When i use rssReader,getItems, all the title form the feed show up in one row. Sorry if my english not well. Hope you understand my question and can give me some solution

    Thanks

    Reply
    • itcuties says:

      Hi Sutadi. It’s nice to hear that our tutorial helped you. If You want to code a ListView displaying an image and some text in a row check out our latest tutorial http://www.itcuties.com/android/how-to-get-running-process-list-and-traffic-statistics/, you might find it useful.

      As for the rssReader.getItems() method it returns a List of RssItems. This class implements toString() method so, in some cases when this method is called behind the scenes you might get a string representation of the list. Don’t know how do you use it but it might happen.

      As for the getTitle method of RssItem class our RSS feed is in version 2.0 and we didn’t have any problems with parsing title. Please check if there is a title tag present in Your feed or does it contain any value.

      Cheers,
      itcuties

      Reply
  2. SHINMIN says:

    Hello! I’m Taiwanese!

    Similarly, my english is not sufficient proficient, so I hope you can understand what I say, thank you very much ^^

    My problem is that if I want to gain the image tag content , do I use this same concepts (RssParseHandler class)

    to get it and show on my new Activity?

    Because my experience is not ample, so can you give me some guides? I’ll very appreciate you ><

    Reply
    • itcuties says:

      Hi Shinmin!
      According to W3 an image is a tag that contains url, title and link tags.
      You can use the same concept as we show in this tutorial. You need to modify RssParseHandler so that when it reaches an image tag it sets some kind of flag indicating that now an image tag is being parsed. Next thing is to modify startElement method to parse sub elements of an image tag but only when that flag is set. Image URL is placed in the url tag.
      When You have an image url in your hands use something like this:

      	ImageView imgView=(ImageView)findViewById([YOUR_IMAGE_VIEW_ID]);
      	imgView.setImageURI(Uri.parse([RSS_IMAGE_URL])); 
      

      Hope that helps. Let us know about the results. Best of luck.
      itcuties

      Reply
  3. Daniel Freyr says:

    I get this error ín logcat “Couldn´t open http://www.itcuties.com/feed/” i have tried couple of feeds what might be happening.

    Reply
    • itcuties says:

      Hi Daniel,
      Does your development device on which you run this app has an GSM modem support?
      Did you set android.permission.INTERNET for the application?
      Does our feed link work in your browser?
      Do other RSS feeds work with our code?

      Send us your code to team[at]itcuties[dot]com. We’ll try to figure it out.

      itcuties

      Reply
  4. Jordi says:

    Can you please make an example how to include descriptions in the app itself? So the content of 1 item will show up on a different / new “page”?

    Reply
    • itcuties says:

      Hi Jordi.
      You need to modify RssParseHandler class to get the description tag value. Do it the same way as the title tag is being processed. Modify RssItem class to hold item’s description data as well.
      Next create a simple view that contains TextView. Create an activity that uses this new view. Set TextView value with the value passed to this activity.
      To read values passed to the activity use this code:

      Bundle bundle = getIntent().getExtras();
      String value = bundle.getString("[YOUR_KEY_HERE]");
      

      Next you need to modify onItemClick method of the ListListener class. You need to start your new activity here and pass a description value.

      Intent intent = new Intent(activity, YourNewActivity.class);
      intent.putExtra("[YOUR_KEY_HERE]", listItems.get(pos).getDescription());
      activity.startActivity(intent);
      

      itcuties

      Reply
      • Jordi says:

        I’ll have a look for it. Thanks in advance!

        Reply
      • Jordi says:

        It isn’t working so far. I’ve upload some files, so I hope you can help me, because I’m just an amateur.

        ItemDescriptionActivity.Java => http://snipt.org/vgBh9
        RssItem.java => http://snipt.org/vgBi5
        ListListener.java => http://snipt.org/vgBj6
        RssParseHandler.java => http://snipt.org/vgCa9
        item.xml => http://snipt.org/vgCb2

        I’m sorry for my English, I’m Dutch.

        Reply
        • itcuties says:

          Try this modifications on your RssParseHandler.java

          1. Add private boolean parsingDescription;
          2. In the startElement method change

          else if ("description".equals(qName)){
          	parsingLink = true;
          }
          

          to

          else if ("description".equals(qName)){
          	parsingDescription = true;
          }
          

          3. In the endElement method change

          else if ("description".equals(qName)){
          	parsingLink = true;
          }
          

          to

          else if ("description".equals(qName)){
          	parsingDescription = true;
          }
          

          4. In the characters method add

          else if (parsingDescription) {
          	if (currentItem != null)
          		currentItem.setDescription(new String(ch, start, length));
          }
          

          Take care.
          itcuties

          Reply
          • Jordi says:

            Sorry, for asking so much but I still get errors:

            10-18 17:48:17.957: W/dalvikvm(627): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
            10-18 17:48:17.987: E/AndroidRuntime(627): FATAL EXCEPTION: main
            10-18 17:48:17.987: E/AndroidRuntime(627): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.itcuties.android.reader/com.itcuties.android.reader.ItemDescriptionActivity}; have you declared this activity in your AndroidManifest.xml?
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1541)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.Activity.startActivityForResult(Activity.java:3351)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.Activity.startActivityForResult(Activity.java:3312)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.Activity.startActivity(Activity.java:3522)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.Activity.startActivity(Activity.java:3490)
            10-18 17:48:17.987: E/AndroidRuntime(627): at com.itcuties.android.reader.listeners.ListListener.onItemClick(ListListener.java:38)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.widget.AbsListView$1.run(AbsListView.java:3529)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.os.Handler.handleCallback(Handler.java:615)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.os.Handler.dispatchMessage(Handler.java:92)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.os.Looper.loop(Looper.java:137)
            10-18 17:48:17.987: E/AndroidRuntime(627): at android.app.ActivityThread.main(ActivityThread.java:4745)
            10-18 17:48:17.987: E/AndroidRuntime(627): at java.lang.reflect.Method.invokeNative(Native Method)
            10-18 17:48:17.987: E/AndroidRuntime(627): at java.lang.reflect.Method.invoke(Method.java:511)
            10-18 17:48:17.987: E/AndroidRuntime(627): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            10-18 17:48:17.987: E/AndroidRuntime(627): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            10-18 17:48:17.987: E/AndroidRuntime(627): at dalvik.system.NativeStart.main(Native Method)

            However this is my AndroidManifest.xml: http://snipt.org/vgHg0

            Thanks for all your support so far.

            Jordi

            Reply
            • itcuties says:

              It’s a pleasure to help you :)
              Just add android:name="android.intent.action.MAIN" (don’t add android:name="android.intent.category.LAUNCHER") configuration (the same way as it is done in ITCutiesReaderAppActivity) to your ItemDescriptionActivity definition.
              Have a nice evening ;)
              itcuties

              Reply
  5. Jordi says:

    With a few changes in my code, I’ve made it to show the description!
    Thanks for all your support!

    Reply
  6. Daniel says:

    Is it possible to make the article open in an activity instead in the browser.

    Thanks in advance

    Reply
    • itcuties says:

      Hi Daniel,
      This is almost the exact same solution that we have talked about with Jord. The difference is that you need to get content:encoded tag contents from the RSS feed.

      itcuties

      Reply
  7. ray says:

    can you post all code about how to get images and description¿? thanks………

    Reply
  8. Divyendu says:

    Hey, For me it gives the IOException. Could’nt read
    Can you help me out ?

    Reply
  9. SSS says:

    Hi,

    Great to see very helpful articles here. Great job !!

    I am a beginner in Android programming. I have a food blog (Blogger) and trying to make an app for the same.
    As I am a novice , please bear with my simple (or silly ;) ) and basic questions :) :)
    I have a few questions regarding converting my food blog to app.

    1. Making an app of my blog means I need to get the RSS feed of my blog, parse it and display the data ina good format in my app. Is this the correct method?

    2. Does the RSS feed contain all the blog data? Or does it show only for a certain period?

    3. Can I access the blogger widgets such as Popular posts, Post Categories etc in my app? Or how can I show them in app ? Does the feed has such data?

    4. Should my app connect to the blog for displaying data? Then it won’t serve the purpose of an app rt?????
    So does that mean my app should display the data only from the RSS feed and give “Go to Blog” as an option?

    5. I haven’t seen any food blog as an app to view as example. Are there any such apps?

    Please help me…

    Thanks in advance…

    Reply
    • itcuties says:

      Hi,
      Ad.1. and 2. Not really. The best way is to connect to WordPress XML-RPC API. Take a look at this solution – http://code.google.com/p/wordpress-java/. Your RSS channel might contain a configured number of items but remember the more items are there the slower channel loads. Mainly RSS channel is being read by RSS Reader applications. You should keep it that way.

      Ad.3. You can read latest data from the RSS feed. If you want to read popular posts use this wordpress-java library that was mentioned above.

      Ad.4. You can get posts data from the WordPress XML-RPC API and display them in the app.

      Ad.5. Don’t know any “food blog” apps as well

      Take care.
      itcuties

      Reply
      • SSS says:

        Thanks a lot for your prompt response.
        But one question I have is I have the blog in Blogger and not WordPress.
        So will there be API’s for Blogger as well? I will check it out as well. :)
        Thanks again for taking time to reply.
        I tried your parsing code and it is so easy to understand and implement.
        Thanks for the help :)

        Reply
  10. anant rao says:

    i dont know why but when i used your code in my application it does not run but when i install your soure code it run individualy as a itc cuties application .
    the only difference in my app is i am not using the main xml instead i have a grid menu in which u select the feed menu then it shall upload the feeds . but i m just getting a plain xml strucutre nothing else .
    can i have some help please regarding this

    Reply
    • itcuties says:

      Hi Anant! Can’t really tell what’s going on. Can you upload your code to github so that we can debug it? Or send us your code at team[at]itcuties.com.

      itcuties

      Reply
  11. Eva says:

    Hi
    I have seen your artical and try it step by step .But the result means that it can’t parser the RSS-the feed is null.
    My android simulator support internet
    I have set android.permission.INTERNET for the application.
    Could you please tell me how to fix it?
    sorry for my poor english

    Reply

    Reply
  12. neema says:

    Thanks for great easy tutorial.
    great code ,works well but…
    but it works only on android 2.3.3 and lower versions
    on android 4.0 your code doesn’t work.

    Reply
    • itcuties says:

      Hi Neema,
      We have just downloaded this tutorial project from http://download.itcuties.com/android-rss-reader/ITCutiesReaderApp.zip.
      After importing it to Eclipse and running on the Virtual Device 4.1 with API Level 16 and GSM Modem Support everything works fine.
      This application also runs on Android 4.0.4. It was tested on the phisical device.
      Can you please tell us exactly where is the problem in your case?

      Cheers,
      itcuties

      Reply
      • neema says:

        Hi, thanks for responding so quick.
        I used your code and ran it on android emulator with o.s 2.3.3 and 2.2 and everything worked fine with no problem at all.
        but when I used your code and ran it on emulator with o.s 4.0 or 4.2 it didn’t work. so I searched stackoverflow and they said we should use to line of code to make it work. and codes are:

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        

        and wow ,it worked on android 4.0 or jelly bean (4.2) perfectly but some people say this way is not logical.
        I don’t know, but as long as this code works for me ,I’m happy unless I find out this has something unappropriated to do with security.

        what do you think?

        Reply
        • itcuties says:

          Hi Neema,
          by calling this code

          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
          StrictMode.setThreadPolicy(policy);
          

          you are disabling detection of all the available resource usage events. Our code only uses network interface. Maybe there is a problem with loading RSS contents duo to network problems. Can’t really tell couse we can run our code on every platform you mentioned.

          You could try calling permitNetwork method instead of the permitAll. We are curiouse if this will give you the same effect.

          itcuties

          Reply
  13. Andrey says:

    Hello your tutorial is very good and helped me to understand xml parsing. but when I insert the address that the program takes off, video is registered in my channel хмл (http://194.28.237.214/Podcast/podcast.xml) and I want that it opened third-party players, you couldn’t help me with it. forgive for my English))

    Reply
    • itcuties says:

      Hi Andrey,

      to play a video from URL use this code

      VideoView video = (VideoView)findViewById(R.id.videoView);
      video.setVideoPath("VIDEO-URL");
      video.start();
      

      You need to parse the enclosure tag attribute url and store it in the RssItem object. Next modify the ListListener.onItemClick method. In this method start a new activity. This new acitvity needs to have a VideoView element. Use the above code in the acitvitiesonCreate method.

      We have done some tests with your videos. The M4V format is not supported by the Android – http://developer.android.com/guide/appendix/media-formats.html

      itcuties

      Reply
      • Andrey says:

        thank you very much, but do not tell me that you like RssItem analyze the url tag and save it

        Reply
        • itcuties says:

          To read tag attribute try this modification of the parser class:

          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;
                  } else if ("enclosure".equals(qName)) {
                      // Get tags attributes number
                      int attrsLength = attributes.getLength();
                      for (int i=0; i<attrsLength; i++) {
                         String attrName = attrs.getQName(i);  // attribute name
                         if ("url".equals(attrName))   // This tag has only one attribute but it is better to check it name is correct
                             currentItem.setVideoURL(attrs.getValue(i));
                  }
              }
          

          Add a videoURL attribute to the RssItem class and appropriate access methods.

          itcuties

          Reply
  14. David says:

    Hello,

    Thank you for such a great tutorial. In the video it was mentioned that performance could be improved for this RSS parser. From what I have read online (new to android development), I think using the AsyncTask function could help as the RSS item data could be read in the background on a different thread. However this is where I get stuck. I have tried a number of attempts to get it working, but with no luck. Would you please be able to set me in the right direction? Your support is appreciated.

    Kind regards

    Reply
  15. yannick says:

    i itcuties can you give me the code how to call another layout with de discription of the rss feed title clicked insted of tge site. tks sore for my ingles

    Reply
  16. Ahmad says:

    Really cute I have to admit! a little distracting but I gave my best to learn and it was helpful. Thank you very much!

    in regards to the question I think for the optimization we have to work a bit on the adapter.
    we can have separate adapter class extending ArrayAdapter and then in the getView method check if the row has been initialized before and exist or it’s == null. then if it was null inflate a view for it. Using Asynctask also could be helpful for the whole experience.
    and if this is not the case then I can’t wait to hear it.

    Again Thank you for the great tutorials, great quality of sound, picture and codes.
    Cheers

    Reply
    • itcuties says:

      Hi Ahmad,

      this code optimization is much simpler then the modifications you are writing about. Analyze ITCutiesReaderAppActivity code flow carefully :)
      Any ideas?

      Cheers,
      itcuties

      Reply
  17. Surjan Singh says:

    Dear Reader,
    I want to display songs in list view After click on songs then play video Using XML Parsing in Android.
    Please help me Anybody.

    My Id – surjans87@gmail.com

    Reply
  18. Joe says:

    Is there a way to get the title and description of the feed (i.e if the feed is a podcast, I want to get the title and description of the podcast) The thing I want to is to be able to “subscribe” to different feeds, show them in a list, and when I click on one it should then show the individual items (what the code does now). Also, do you guys have a tutorial and how to add all this info to a database?, so that we don’t have to load the info every time we launch app

    Thank you very much for the tutorial.

    Reply
  19. Ramamoorthi says:

    Thank you for your useful tutorial about creating Android App using RssParser. This narrated helpfully to develop an RssReader from Feed of a website. It will be helpful if you give tips/tutorial for creating an up Which display web content in the app itself instead of being directed to website.Also give some material download links.

    Reply
  20. asif says:

    Hi,
    I’m getting error after Running your application in Eclipse.
    The error is :
    ExpatReader DTD handlers aren’t supported.

    Please Help me Out….
    thanks…..

    Reply
    • itcuties says:

      Hi Asif,

      are you lounching our code without any changes?
      You are reading and parsing itcuties RSS channel? If not check if you RSS XML is valid.
      It seems that Android 2.1 had a bug which resulted in the error that you are ending with. Check here: http://code.google.com/p/android/issues/detail?id=4286. This bug was fixed in Froyo 2.2 so maybe you should try to change the project library to 2.2+… Right click your project, then pick Properties, then Android. In the Project Build Target section pick a target platform which is over the 2.1 specification. Rebuild and rerun your application.
      Hope this helps. Let us know about the results.

      Take care,
      itcuties

      Reply
    • itcuties says:

      Actually reruning this application on Android 2.2+ platform will help you :)

      itcuties

      Reply
  21. Duke says:

    Hi,

    i copied your (written, not video!) tutorial but its not working for me :(. My app only shows blanko page with no entries. Thats weird because when I started yours it works. I also have that Internet-Permission.

    The only difference in Code i have is this line:
    ” i.setData(Uri.parse(((Rssitem) listItems.get(pos)).getLink())); ”

    I had to do a Cast because “object” had no “getLink()”. Anyway, it makes no sense to me how yours is working but mine not with the same code =(

    Reply
    • Duke says:

      Oh I got it:

      In AndroidManifest.xml i had: android:minSdkVersion=”17″ /> instead of android:minSdkVersion=”7″ />

      If I change it this way it will work but that makes no sense. Why should something like that not work on Android 4.2 :0?

      Reply
      • itcuties says:

        Hi Duke,
        thanks for your comment. There was an error in our code snippets published on the site – video and the code that can be downloaded was ok. The type of the List data collection used to store RSS items needs to be changed from “List” to “List<RssItem>”. This way you don’t need to perform the cast where you get an item from the items list.
        i.setData(Uri.parse(listItems.get(pos).getLink())); is ok now :)

        As for the lowering the android:minSdkVersion value you have extended number of platforms that your application can run on.
        Are there any major differences in org.xml.sax.* package implementation between the API 7 and API 17 versions? Maybe there are, and this is why while using API 17 version the URL doesn’t parse correctly.
        Where you parsing our RSS channel or some other channel? Maybe there are some “strange” signs in the URL that you are parsing and this is why it doesn’t parse at all (with API v.17).

        Take IT easy,
        itcuties

        Reply
        • Duke says:

          Hi,
          thanks for answering :)

          What do you mean by change from List to List?
          Anyway, if I run the app with API17 instead of API 7 logcat tells me: “Couldn´t open http://www.itcuties.com/feed/” which seems to be the reason why I got no results.
          You got any ideas ?

          Reply
          • itcuties says:

            Oh, something went wrong with the HTML tag in the previous answer. We ment “List” to “List<RssItem>” :)
            As for the API 17 error it seems that it is a bug.

            Reply
            • Duke says:

              Just for your interest: I found the reason :)

              It seems since Android 4.0 you have to encapsulate network activities (especially in MainActivitiy). I solved this by using AsyncTask (which you already had done according to one of your comments to other users, thx again, that helped me ;) )

              Reply
  22. Jose says:

    Im trying this tutorial to implement something similar and the only thing I change is the website, now I have gotten it to work with other websites by just changing the url, now the only problem that I am having is that it crashes with this particular website..

    Do you know what it might be?
    http://feeds.feedburner.com/lasierranews

    Thanks in advance

    Reply
    • itcuties says:

      Hi Jose,
      It seems that you have invalid signs in your RSS text.
      After changing “ to ”
      and ’ to ‘ it works fine :)

      Here is the correct RSS XML file. Try this one.
      http://download.itcuties.com/tmp/lasierranews-itc-test.xml

      Cheers,
      itcuties

      Reply
      • Jose says:

        What do you mean by changing “to” and ‘to’?

        Thanks for all the help this tutorial is great.

        Reply
          • Jose says:

            Is there a way to handle an exception to let the string pass through?

            For ex.

            if(string == ‘ ‘ ‘):
            then throw it away into a separate string?

            Reply
            • itcuties says:

              Hi Jose,
              If you want to handle parsing errors “in the parser” all you need to do is implement error or fatalError methods in your parse handler class which extends DefaultHandler. So in our example code this should look like this:

              RssParseHandler.java

              package com.itcuties.android.reader.util;
              
              import java.util.ArrayList;
              import java.util.List;
              
              import org.xml.sax.Attributes;
              import org.xml.sax.SAXException;
              import org.xml.sax.SAXParseException;
              import org.xml.sax.helpers.DefaultHandler;
              
              import android.util.Log;
              
              import com.itcuties.android.reader.data.RssItem;
              
              /**
               * SAX tag handler
               * 
               * @author ITCuties
               *
               */
              public class RssParseHandler extends DefaultHandler {
              
              	private List<RssItem> rssItems;
              	
              	// Used to reference item while parsing
              	private RssItem currentItem;
              	
              	// Parsing title indicator
              	private boolean parsingTitle;
              	// Parsing link indicator
              	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 warning(SAXParseException e) throws SAXException {
              		Log.e("warning","Hello warning");
              		// Custom warning handling here...
                  }
              
                  @Override
                  public void error(SAXParseException e) throws SAXException {
                      Log.e("error","Hello error");
                      // Custom error handling here...
                  }
              
                  @Override
                  public void fatalError(SAXParseException e) throws SAXException {
                  	Log.e("fatalError","Hello fatalError");
                  	// Custom fatalError handling here...
                  }
              	
              	@Override
              	public void characters(char[] ch, int start, int length) throws SAXException {
              		// Debug the incoming contents
              		Log.d("characters", new String(ch, start, length));
              		
              		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;
              			}
              		}
              	}
              	
              }
              

              Surprised that warning, error and fatalError do nothing special? We were surprised that those methods are not called by the Android when there is something wrong with the XML stream being parsed. We were testing it on 2.2 and 4.2 platforms. Does anyone know if there is some BUG maybe and those method are not called? … Let us know…
              Anyway… We came up with a HOT fix. All you need to do is get rid of the characters that are invalid and crash the parsing process. Here is our new RssReader code.

              RssReader.java

              package com.itcuties.android.reader.util;
              
              import java.io.ByteArrayInputStream;
              import java.io.InputStream;
              import java.net.URL;
              import java.util.List;
              
              import javax.xml.parsers.SAXParser;
              import javax.xml.parsers.SAXParserFactory;
              
              import com.itcuties.android.reader.data.RssItem;
              
              /**
               * Class reads RSS data.
               * 
               * @author ITCuties
               *
               */
              public class RssReader {
              	
              	private String rssUrl;
              
              	/**
              	 * Constructor
              	 * 
              	 * @param rssUrl
              	 */
              	public RssReader(String rssUrl) {
              		this.rssUrl = rssUrl;
              	}
              
              	/**
              	 * Get RSS items.
              	 * 
              	 * @return
              	 */
              	public List<RssItem> getItems() throws Exception {
              		// SAX parse RSS data
              		SAXParserFactory factory = SAXParserFactory.newInstance();
              		SAXParser saxParser = factory.newSAXParser();
              
              		RssParseHandler handler = new RssParseHandler();
              		
              		// FIX: Invalid characters FIX here - start
              		// Create the URL to the RSS resource
              		URL rssURL = new URL(rssUrl);
              		// Open an input stream to the rss channel
              		InputStream rssInputStream = rssURL.openStream();
              		// This is the buffer for the valid RSS contents
              		StringBuffer rssContents = new StringBuffer();
              		// Buffer to read bytes
              		int byteRead = -1;
              		// Read bytes one by one from the RSS input stream until there is something to read
              		while ((byteRead = rssInputStream.read()) != -1) {
              			// Convert byte being read to char
              			char charRead = (char)byteRead;
              			// If the sign being read is invalid then don't add it to the resulting valid RSS contents buffer
              			if (charRead != '’' && charRead != '“') // This are the two problematic characters in your case
              				rssContents.append(charRead);
              		}
              		
              		// Create the valid rss input stream from the StringBuffer using ByteArrayInputStream
              		InputStream rssValidInputStream = new ByteArrayInputStream(rssContents.toString().getBytes());
              		// Parse RSS XML that contains ONLY VALID characters
              		saxParser.parse(rssValidInputStream, handler);
              		// FIX: Invalid characters FIX here - end
              		
              		// Old line
              		//saxParser.parse(rssUrl, handler);
              		
              		return handler.getItems();
              		
              	}
              }
              

              Hope this helps. Take care and take IT easy ;)
              itcuties

              Reply
              • Jose says:

                Thanks,

                One more thing I was looking at previous snipt codes, where you helped them work on a description, how is it possible tom implement it with the parsing, since the parsing is a bit different?

                Reply
                • itcuties says:

                  Hi Jose,

                  you mean that description tag has < ![CDATA[ Description text ]]> element?

                  You can call this code to get the description contents.

                  String content = new String(ch, start, length);
                  content = content.replaceAll("<!\\[CDATA\\[", "");
                  content = content.replaceAll("]]>", "");
                  

                  Cheers,
                  itcuties

                  Reply
  23. Jonny says:

    Hi what an amazing tutorial thanks for making this
    I have a question, Is there a way to change the font color of the text in list view?

    Reply
  24. fakhria says:

    Hi , thank you for this tutorial .
    I have a problem , and it’s not problem in the same time !

    when I run or debug the pro. nothing appear to me , the screen become black and nothing appear !

    + how can I change the site ? I want to get the rss from another site not http://www.itcuties.com/feed/ , but even I change the site the screen become black .

    see the pic.

    http://im33.gulfup.com/Hcw0n.png

    how can I solve it ?

    Reply
  25. m1lesh says:

    Hello,

    I am trying to show description on click, but application crashes on click. I uploaded it to github, Can you check it?

    https://github.com/m1lesh/ITCutiesReaderApp2/tree/ITCutiesReaderApp

    Thanks.

    Reply
  26. Bubba says:

    Hi
    I am trying to parse the following Rss code with your handler
    0915 : Heir Hunters2/20. The team solve a 20-year-old case, and reveal the story of a heroic pilot in the family. Also in HD.

    I want to be able to separate the Time from the Title of the Tv show with the “:” and I have been trying to use the java.util.StringTokenizer; to split the time and title up but have bee so far unsuccessful.

    would you be able to provide any hints on who to do this

    thanks

    Reply
    • itcuties says:

      Hi Bubba,

      Try replaceAll method of the String class.
      Here is the example:

      System.out.println("Test:Test:Test".replaceAll("\\:", "."));
      

      Results in:

      Test.Test.Test
      

      Cheers,
      ITCuties

      Reply
  27. Fakhria says:

    welcome again ,
    see what comes to me here ,

    http://im32.gulfup.com/GUimh.png

    is that means I have something wrong ?
    and I am sorry for my bad English :(

    Reply
  28. Pratik says:

    Hi, thanks for such a great tutorial. I liked it but could have been more helpful if it could get the data from other website too. Whenever i change the url and try with another one, the screen turns black. Is there any solution to it?

    Reply
  29. Pratik says:

    Hi again, i wanted to ask can i add multiple websltes say two and also how can i display the time, day and the source for the same…

    Reply
    • itcuties says:

      This code parses only one RSS feed at a time. You can modify it to parse any number of feeds. Just keep one list of RssItem elements in the activity and call the RssReader getItems method for each feed. Append this method results to the list of the RssItems you keep in the acitvity.
      If you want to display something more than just an item’s title please refer to our other tutorial where we display process information in a list with an image and a text. You will need to implement the your ListAdapter. Watch our tutorial – http://www.itcuties.com/android/how-to-get-running-process-list-and-traffic-statistics/.

      itcuties

      Reply
  30. Jose says:

    What about adding the date? Is there a specific way to show the date?

    Reply
  31. itRosh says:

    Hi !

    I get image url Null

    I implement like this
    in RssParseHandler class

    else if (parsingImageURL) {
    if (currentItem != null) {
    currentItem.setUrl(new String(ch, start, length));

    }
    And in RssItem class

    public void setUrl(String url) {
    this.url = url;
    }
    when I call getUrl method Iget null. My rss feed has url tag.

    Any help will appropriate

    Reply
  32. itRosh says:

    Hi ! Thank you for replying. I fix it. I forgot to implement endElement method until tag. Thank you CUTIES :) it is great tutorial and keep up the good work.

    Reply
  33. itRosh says:

    Correction: until tag = until ” ” tag

    Reply
  34. itRosh says:

    Ok I can’t post tags here !! I mean “image” tag

    Reply
  35. Ali says:

    Thank you

    Reply
  36. Nikolas says:

    hi i have a problem…

    I have to parse an xml file from a website;

    I’m not able to parse html tags and it stops when it finds the first “<"

    Reply
    • itcuties says:

      Hi Nikolas,
      What is the RSS feed’s URL that you are trying to parse?
      You can also send us your project to team@itcuties.com. We will try to find the solution.

      Have a nice day,
      itcuties

      Reply
      • George says:

        First of all thank you for helping so far :)
        I have the same problem here!
        I tried to fix the problem by injecting the content:encoded into a string and then to a new activity on a webview as raw html data which works like a charm but the parser continious to malfunction parsing html tags. Please help me!

        Reply
  37. Taras says:

    Hi.I downloaded the source code and it does not work, I do not change it. The application starts with a black screen and nothing is displayed. I tried it on Nexus 7.

    Reply
  38. Approfi says:

    Hi ITCuties,
    I don’t know what is the mistake in my code.
    The only error message from LogCat i get is “Couldn’t open http://www.itcuties.com/feed/
    Thanks for help in advance,
    Approfi

    Reply
  39. MoBr114 says:

    Hello ITCuties,

    my problem is that the RssItems are loaded but their titles arent shown theres just a text like this:
    com.mypackage.myapp.data.RssItem@4204e078.
    Thanks for your help in advance,

    MoBr114

    Reply
    • itcuties says:

      Hi there MoBr114,

      Does your RssItem class have the toString method? Does it return title attribute value?

      Take care,
      itcuties

      Reply
      • MoBr114 says:

        Thanks for your answer,
        I understand what is the problem but I have no idea where I have to put the toString()
        Eventually you can help me

        MoBr114

        Reply
        • itcuties says:

          Hi,

          your RssItem class code should be similar to this one…

          package com.itcuties.android.reader.data;
          /**
           * This code encapsulates RSS item data.
           * Our application needs title and link data.
           *
           * @author ITCuties
           */
          public class RssItem {
              // item title
              private String title;
              // item link
              private String link;
              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;
              }
          }
          

          Have a nice evening,
          itcuties

          Reply
  40. uli1771 says:

    Can i add short part of the content just like a preview or description to the listview?

    Reply
  41. uli1711 says:

    I want to do something like gReader
    I’m using a wordpress blog

    Sorry that i ask so much

    Reply
  42. Rajat Jain says:

    Hey
    I am having a weird problem. I changed the URL from which this application parses feeds (and I used almost 2-3 different URLs), and some items in the list started to have incomplete titles. The numbers of these items is at maximum one or two, and the occurrence is also random, but this definitely is a bug. Can you guys explain what’s going on.

    Here’s the three links I used:
    http://coreyclaytonlnp.wordpress.com/feed/
    http://www.thehindu.com/news/international/?service=rss
    http://www.thehindu.com/news/?service=rss

    Reply
    • itcuties says:

      Hello Rajat Jain,
      Yes, there is a little bug in this code. Sometimes when RSS data is being read from the Internet, as in our example, parser calls characters method multiple times when reading tag contents. Remember that SAX is a stream parser and if the stream comes from the Internet some network delays might occur. Try using this fixed code and you are good ?

      package com.itcuties.multicategoryrssreader.util;
      
      import java.util.ArrayList;
      import java.util.List;
      
      import org.xml.sax.Attributes;
      import org.xml.sax.SAXException;
      import org.xml.sax.helpers.DefaultHandler;
      
      import com.itcuties.multicategoryrssreader.data.RssItem;
      
      /**
       * SAX tag handler
       * 
       * @author ITCuties
       *
       */
      public class RssParseHandler extends DefaultHandler {
      
      	private List<RssItem> rssItems;
      	
      	// Used to reference item while parsing
      	private RssItem currentItem;
      	
      	// Parsing title indicator
      	private boolean parsingTitle;
      	// A buffer used to build current title being parsed
      	private StringBuffer currentTitleSb;
      	
      	// Parsing link indicator
      	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;
      			
      			currentTitleSb = new StringBuffer();
      		} 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;
      			
      			// Set item's title when we parse item->title tag not the channel title tag
      			if (currentItem != null) {
      				// Set item's title here
      				currentItem.setTitle(currentTitleSb.toString());
      			}
      			
      		} else if ("link".equals(qName)) {
      			parsingLink = false;
      		}
      	}
      	
      	@Override
      	public void characters(char[] ch, int start, int length) throws SAXException {
      		if (parsingTitle) {
      			if (currentItem != null) {
      				// Here we append the title to the buffer due to network issues.
      				// Sometimes this characters method is called multiple times for a tag contents.
      				currentTitleSb.append(new String(ch, start, length));
      			}
      		} else if (parsingLink) {
      			if (currentItem != null) {
      				currentItem.setLink(new String(ch, start, length));
      				parsingLink = false;
      			}
      		}
      	}	
      }
      

      Take care,
      itcuties

      Reply
  43. Leonardo says:

    Hello! I’m Leonardo!
    Thank you for the tutorial. I want to add the option to save the information that we received from the feed
    and then to edit this information and then to show it again .
    can you tell in which part of the code i can get the information , save it and then show it agan .
    Maybe you have an idea what is the best way to do it?

    Reply
    • itcuties says:

      Hi Leonardo,
      Take a look on our tutorial where we show how to read, write and delete in SQLite database in Android – http://www.itcuties.com/android/sqlite-example-the-todo-application

      The best place in the code to store data in a database is after it’s has been read and parsed from the RSS channel – in the ITCutiesReaderAppActivity code. There you have a list of RSSItem objects which you can store in a database. As for reading back data to display, this activity’s code is the best place as well.

      Write a helper class which operates on a database by storing and reading back RSS data. Use it to store parsed data and read it back before the ArrayAdapter is created in the ITCutiesReaderAppActivity.

      Have a nice day,
      itcuties

      Reply
  44. Michael van der Puije says:

    Hello there,
    I’m trying to make my description class show the description when i click on an RSS Item so i followed Jordi’s solution but i realised that he couldn’t get his description class to work until he “made a few changes to his code” (http://www.itcuties.com/android/how-to-write-android-rss-parser/#comment-191) which wasnt explained. Can you please share those changes? Thanks.

    Reply
    • itcuties says:

      We are working on an application that will contain this functionality. Stay tuned :)

      itcuties

      Reply
  45. Karim says:

    Thank you for this tutorial, I followed every step but when I ran the application on the AVD it displayed nothing and I got an error in the log cat saying “couldn’t open http:// ———-”.
    I added the Internet permission.
    And I tried to use the browser on the AVD and it works.
    can you help me with this.

    Thank you,
    Karim.

    Reply
  46. Mohammad Assad says:

    Hi,

    I am trying to parse in google news link: https://news.google.com/news/feeds?hl=en&gl=us&q=Cricket&um=1&ie=UTF-8&output=rss

    Everything is working correctly, however when I click on a list view the incomplete url opens; for eg instead of

    http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFFB16QSs6-6CPHaJuP_V6oE4odDw&url=http://www.espncricinfo.com/india/content/story/638894.html

    only http://news.google.com/news/url?sa opens.

    Please suggest a fix

    Reply
  47. Yousef says:

    Thanks for your helpful topic.
    Actually I could run ur project and I add another activity to ur project to show the content with title of the news, however I can get the title but it show Null in WebView of content.
    I go through all the comments to find answer but i just give address of (http://www.itcuties.com/android/how-to-get-running-process-list-and-traffic-statistics/#display-data-in-a-form-of-listview) I check this article too but i couldnt solve my problem.

    I also try to get the publishdate of articale which is not cdata, also i got null. the only things i can get in my activity is Link and Title.

    Reply
  48. itcuties says:

    Hi Yousef,
    Here is the fixed code that parses title, link, description and pubDate tags. We post it for others who may have similar problems. Rest of the issues we’ll discuss on PRIV :)

    package com.example.tester;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    /**
     * SAX tag handler. The Class contains a list of RssItems which is being filled while the parser is working
     * @author ITCuties
     */
    public class RssParseHandler extends DefaultHandler {
     
    
    	// List of items parsed
        private List<RssItem> rssItems;
        // We have a local reference to an object which is constructed while parser is working on an item tag
        // Used to reference item while parsing
        private RssItem currentItem;
        // We have two indicators which are used to differentiate whether a tag title or link is being processed by the parser
        // Parsing title indicator
        private boolean parsingTitle;
        // Parsing link indicator
        private boolean parsingLink;
        // Parsing link indicator
        private boolean parsingContent;
      
        private StringBuffer currentContentSb;
        
        private boolean parsingPubdate;
        
        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 ("link".equals(qName)) {
                parsingLink = true;
                
            } else if ("title".equals(qName)) {
            	parsingTitle = true;
            	
            } else if ("description".equals(qName)) {
            	if (currentItem != null) {
            		parsingContent = true;
            		currentContentSb = new StringBuffer();
            	}
            }
            else if ("pubDate".equals(qName)) {
            	parsingPubdate = true;
            }
        }
        
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if ("item".equals(qName)) {
                rssItems.add(currentItem);
                currentItem = null;
                
            } else if ("link".equals(qName)) {
                parsingLink = false;
                
            } else if ("title".equals(qName)) {
            	parsingTitle = false;
            
        } else if ("description".equals(qName)) {
        	parsingContent = false;
        	
        	if (currentItem != null)
        		currentItem.setContent(currentContentSb.toString());
        }
            else if ("pubDate".equals(qName)) {
            	parsingPubdate = 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;
                }
            } else if (parsingContent) {
                    if (currentItem != null) {
                        
                        currentContentSb.append(new String(ch, start, length));
                       
                    }
            } else if (parsingPubdate) {
            		if (currentItem != null) {
                            currentItem.setPubDate(new String(ch, start, length));
                            parsingPubdate = false;
            		}
            }
            
        }
    }
    

    Take care,
    itcuties

    Reply
  49. nikhil says:

    Hi !
    I worked on your tutorial but it seems after launching the app from my emulator ….it FREEZES…. i mean there’s nothing except of a blank screen ….
    I even downloaded the apk available at your site and it worked just great !!!
    Can you please help me figure out why you apk is working smooth and but the same code shows none in my emulator .

    Reply
    • itcuties says:

      Hello Nikhil,
      Are there any errors in the LogCat?
      What version of Android does your emulator run on?

      itcuties

      Reply
      • nikhil says:

        Hi !
        I couldn’t really figure out the error meaning so i am posting the log which appeared as RED in font color .

        06-19 12:06:47.458: E/Zygote(32): setreuid() failed. errno: 2
        06-19 12:07:08.997: E/Zygote(32): setreuid() failed. errno: 17
        06-19 12:07:12.338: E/BatteryService(67): usbOnlinePath not found
        06-19 12:07:12.338: E/BatteryService(67): batteryVoltagePath not found
        06-19 12:07:12.338: E/BatteryService(67): batteryTemperaturePath not found
        06-19 12:07:12.368: E/SurfaceFlinger(67): Couldn’t open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
        06-19 12:07:12.628: E/SensorService(67): couldn’t open device for module sensors (Invalid argument)
        06-19 12:07:21.428: E/System(67): Failure starting core service
        06-19 12:07:21.428: E/System(67): java.lang.SecurityException
        06-19 12:07:21.428: E/System(67): at android.os.BinderProxy.transact(Native Method)
        06-19 12:07:21.428: E/System(67): at android.os.ServiceManagerProxy.addService(ServiceManagerNative.java:146)
        06-19 12:07:21.428: E/System(67): at android.os.ServiceManager.addService(ServiceManager.java:72)
        06-19 12:07:21.428: E/System(67): at com.android.server.ServerThread.run(SystemServer.java:206)
        06-19 12:07:21.458: E/EventHub(67): could not get driver version for /dev/input/mouse0, Not a typewriter
        06-19 12:07:21.458: E/EventHub(67): could not get driver version for /dev/input/mice, Not a typewriter
        06-19 12:07:22.197: E/SoundPool(67): error loading /system/media/audio/ui/Effect_Tick.ogg
        06-19 12:07:22.197: E/SoundPool(67): error loading /system/media/audio/ui/KeypressStandard.ogg
        06-19 12:07:22.197: E/SoundPool(67): error loading /system/media/audio/ui/KeypressSpacebar.ogg
        06-19 12:07:22.197: E/SoundPool(67): error loading /system/media/audio/ui/KeypressDelete.ogg
        06-19 12:07:22.207: E/SoundPool(67): error loading /system/media/audio/ui/KeypressReturn.ogg
        06-19 12:07:22.337: E/UsbObserver(67): java.lang.NullPointerException
        06-19 12:07:22.337: E/UsbObserver(67): at com.android.server.UsbObserver.init(UsbObserver.java:131)
        06-19 12:07:22.337: E/UsbObserver(67): at com.android.server.UsbObserver.(UsbObserver.java:65)
        06-19 12:07:22.337: E/UsbObserver(67): at com.android.server.ServerThread.run(SystemServer.java:402)
        06-19 12:07:23.737: E/ThrottleService(67): Could not open GPS configuration file /etc/gps.conf
        06-19 12:07:27.468: E/logwrapper(158): executing /system/bin/tc failed: No such file or directory
        06-19 12:07:27.568: E/logwrapper(159): executing /system/bin/tc failed: No such file or directory
        06-19 12:07:27.608: E/logwrapper(160): executing /system/bin/tc failed: No such file or directory
        06-19 12:07:52.552: E/ActivityManager(67): Start proc android.process.media for broadcast com.android.providers.downloads/.DownloadReceiver: pid=205 uid=10000 gids={1006, 1015, 2001, 3003}Load: 4.71 / 1.18 / 0.39
        06-19 12:07:52.552: E/ActivityManager(67): CPU usage from 1331ms to -11623ms ago:
        06-19 12:07:52.552: E/ActivityManager(67): 42% 67/system_server: 29% user + 12% kernel / faults: 2084 minor 2 major
        06-19 12:07:52.552: E/ActivityManager(67): 11% 182/android.process.acore: 8.3% user + 3% kernel / faults: 1767 minor 4 major
        06-19 12:07:52.552: E/ActivityManager(67): 10% 132/com.android.launcher: 9.1% user + 1.1% kernel / faults: 1021 minor 2 major
        06-19 12:07:52.552: E/ActivityManager(67): 7.2% 126/com.android.phone: 5.5% user + 1.6% kernel / faults: 358 minor 1 major
        06-19 12:07:52.552: E/ActivityManager(67): 6.1% 79/bootanimation: 4.6% user + 1.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 5.2% 129/com.android.systemui: 3.9% user + 1.3% kernel / faults: 716 minor 2 major
        06-19 12:07:52.552: E/ActivityManager(67): 2% 40/adbd: 0.2% user + 1.7% kernel / faults: 29 minor
        06-19 12:07:52.552: E/ActivityManager(67): 1.4% 120/jp.co.omronsoft.openwnn: 0.5% user + 0.9% kernel / faults: 16 minor
        06-19 12:07:52.552: E/ActivityManager(67): 0.6% 162/com.android.settings: 0.3% user + 0.3% kernel / faults: 130 minor
        06-19 12:07:52.552: E/ActivityManager(67): 0.1% 31/rild: 0% user + 0% kernel / faults: 1 minor
        06-19 12:07:52.552: E/ActivityManager(67): 0.3% 32/zygote: 0.1% user + 0.1% kernel / faults: 16 minor
        06-19 12:07:52.552: E/ActivityManager(67): 0% 37/qemud: 0% user + 0% kernel / faults: 1 minor
        06-19 12:07:52.552: E/ActivityManager(67): 0% 33/mediaserver: 0% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): +0% 197/sh: 0% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): +0% 198/app_process: 0% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): +0% 205/zygote: 0% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 100% TOTAL: 71% user + 27% kernel + 0% irq + 0.4% softirq
        06-19 12:07:52.552: E/ActivityManager(67): CPU usage from 7951ms to 9737ms later with 99% awake:
        06-19 12:07:52.552: E/ActivityManager(67): 35% 67/system_server: 27% user + 7.9% kernel / faults: 32 minor
        06-19 12:07:52.552: E/ActivityManager(67): 11% 75/SurfaceFlinger: 8.4% user + 2.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 8.9% 97/WindowManagerPo: 8.4% user + 0.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 6.4% 80/ActivityManager: 1.9% user + 4.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 4.9% 199/Thread-53: 4.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 3.4% 96/WindowManager: 3.4% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 1.9% 74/Binder Thread #: 1.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 1.4% 78/er.ServerThread: 0.9% user + 0.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 1.4% 193/Binder Thread #: 1.4% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.9% 67/system_server: 0% user + 0.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.9% 73/Binder Thread #: 0.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.9% 186/Binder Thread #: 0.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.9% 187/Binder Thread #: 0.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.9% 192/Binder Thread #: 0.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.4% 72/Compiler: 0.4% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.4% 98/InputDispatcher: 0% user + 0.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): +0% 204/Thread-54: 0% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 12% 182/android.process.acore: 6.6% user + 6.1% kernel / faults: 34 minor
        06-19 12:07:52.552: E/ActivityManager(67): 5.6% 182/d.process.acore: 4% user + 1.5% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 4% 183/HeapWorker: 0.5% user + 3.5% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 9.8% 126/com.android.phone: 9.3% user + 0.4% kernel / faults: 77 minor
        06-19 12:07:52.552: E/ActivityManager(67): 6.1% 126/m.android.phone: 5.1% user + 0.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 2.8% 138/GC: 2.8% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 1.4% 174/RILReceiver: 0.9% user + 0.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.9% 173/RILSender: 0.9% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.4% 141/Compiler: 0.4% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 8.2% 132/com.android.launcher: 6.3% user + 1.9% kernel / faults: 207 minor
        06-19 12:07:52.552: E/ActivityManager(67): 4.3% 132/ndroid.launcher: 3.8% user + 0.4% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 2.9% 170/launcher-loader: 1.9% user + 0.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 8% 198/app_process: 6.5% user + 1.5% kernel / faults: 206 minor
        06-19 12:07:52.552: E/ActivityManager(67): 4.7% 79/bootanimation: 3.7% user + 0.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 5.6% 83/BootAnimation: 4.7% user + 0.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.6% 32/zygote: 0.3% user + 0.3% kernel / faults: 16 minor
        06-19 12:07:52.552: E/ActivityManager(67): 1.8% 129/com.android.systemui: 1.4% user + 0.4% kernel / faults: 11 minor
        06-19 12:07:52.552: E/ActivityManager(67): 2.3% 129/ndroid.systemui: 1.4% user + 0.9% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 1% 31/rild: 0.5% user + 0.5% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.5% 53/rild: 0% user + 0.5% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.5% 55/rild: 0% user + 0.5% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 0.1% 37/qemud: 0.1% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): +0% 205/zygote: 0% user + 0% kernel
        06-19 12:07:52.552: E/ActivityManager(67): 100% TOTAL: 73% user + 26% kernel

        Reply
        • nikhil says:

          And Yes my target virtual device details are :

          device: 4.0″ WVGA (480 x800 hdpi)
          target : Android 2.3.3 API Level 10
          Cpu : ARM

          Android Manifest File :

          android:minSdkVersion=”8″
          android:targetSdkVersion=”17″

          and Internet permission is also provided .

          Reply
          • itcuties says:

            Hello Nikhil,
            We are experiencing no problem while running this code on the same platform you did. Check out our screencast that we did quickly http://www.youtube.com/watch?v=v3VYprccKe8. The major setting are the same as yours.
            There has to be something wrong with your emulator. Are you running other applications that use Internet connection on this device with no problem?

            Take care,
            itcuties

            Reply
  50. SWE says:

    Even i am experiencing the same problem as Nikhil.
    Its not getting installed on my emulator 4.0 when i run it in eclipse. it just says this and stops.
    Android Launch!
    [2013-06-19 18:44:28 - ITCutiesReaderApp] adb is running normally.
    [2013-06-19 18:44:28 - ITCutiesReaderApp] Performing com.itcuties.android.reader.ITCutiesReaderAppActivity activity launch
    [2013-06-19 18:44:29 - ITCutiesReaderApp] Automatic Target Mode: Preferred AVD ‘emulator_high’ is not available. Launching new emulator.
    [2013-06-19 18:44:29 - ITCutiesReaderApp] Launching a new emulator with Virtual Device ‘emulator_high’

    Reply
  51. SWE says:

    Thanks a lot for your help ITCuties. That worked.. :)
    You are doing a very good job which is helping a lot for beginners like us.
    Can you please share the code to display an image as well in the list..

    Reply
  52. Ace says:

    Hi! :) First of all, a big thank you for those great tutorials and sorry for any mistake made writing in English.
    Mixing them up I was able to create my first Android App and I’ìm trying to add functions to make it better.
    I’ve got a content in my RSS feed that contains HTML content with the first image.
    So I’ve added

    private boolean parsingNotizia;

    in RssParserHandler

    else if ("contenuto".equals(qName)) {
    			parsingNotizia = true;
    		}
    

    in startElement

    else if ("contenuto".equals(qName)) {
    			parsingNotizia = false;
    	}
    

    in endElement

    else if (parsingNotizia) {
    			if (currentItem != null) 
    				currentItem.setNotizia(new String(ch, start, length));
    		} 
    

    in Characters.

    In RssItem

    private String contenuto; 
    public String getNotizia() {
    	return contenuto;
    	}
    
    public void setNotizia(String contenuto) {
    	this.contenuto = contenuto;
        }
    

    I’ve also an intent that opens the list element in a new activity and I pass the “contenuto” content to this to show the full content in a new view. It shows nothing… :) but if I pass “description” it works. If I change the “print” element of the list and add the “contenuto” variable, it shows nothing too. Am I missing something?

    Reply
  53. Gandharv says:

    Hi i am working on a rssreader app which contains tags which actually has image url links as of now the rssreaderparser recognizes the tag setimage sets the url (this.url=url) which is actually the url string not the image and tostring displays the url. What i want is to dispay the image instead of links. Where do i need to make changes ? and what changes? May i mail u my application ?

    Reply
    • itcuties says:

      Hello,
      If you have an image URL all you need to do is something like this…

      // Get the image contents
      URL url = new URL("YOUR_IMAGE_URL");
      InputStream is = (InputStream)url.getContent();
      Drawable drawable = Drawable.createFromStream(is,"src");
      // Get your ImageView and set the drawable
      image.setImageDrawable(drawable);
      

      Hope this works for you. Let us know.

      Take care,
      itcuties

      Reply
      • Gandharv says:

        first of all thanks ITCuties
        May i know what is varibale image in image.setImageDrawable ?

        Reply
        • itcuties says:

          This image variable represents your variable that you probably will use to display an image. Depending on your code you will have to obtain a reference to it by calling something like this:

          ImageView image = (ImageView) findViewById(R.id.[YOUR_IMAGEVIEW_ID]);
          

          itcuties

          Reply
  54. PC says:

    Hi,

    I downloded your code and tried it. But I am getting the error, “couldn’t open http://…”

    I have checked the following:-

    1. The feed is valid
    2. I have set the internet permission (as I am using your code)

    could you please help me out here.

    Reply
  55. PC says:

    Following is the stack trace for the error:-

    07-03 03:20:12.003: W/System.err(875): java.io.IOException: Couldn’t open http://www.itcuties.com/feed/
    07-03 03:20:12.010: W/System.err(875): at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
    07-03 03:20:12.010: W/System.err(875): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
    07-03 03:20:12.010: W/System.err(875): at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
    07-03 03:20:12.010: W/System.err(875): at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
    07-03 03:20:12.010: W/System.err(875): at com.itcuties.android.reader.util.RssReader.getItems(RssReader.java:41)
    07-03 03:20:12.010: W/System.err(875): at com.itcuties.android.reader.ITCutiesReaderAppActivity.onCreate(ITCutiesReaderAppActivity.java:36)
    07-03 03:20:12.010: W/System.err(875): at android.app.Activity.performCreate(Activity.java:5104)
    07-03 03:20:12.010: W/System.err(875): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    07-03 03:20:12.020: W/System.err(875): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    07-03 03:20:12.020: W/System.err(875): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    07-03 03:20:12.020: W/System.err(875): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    07-03 03:20:12.020: W/System.err(875): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    07-03 03:20:12.020: W/System.err(875): at android.os.Handler.dispatchMessage(Handler.java:99)
    07-03 03:20:12.020: W/System.err(875): at android.os.Looper.loop(Looper.java:137)
    07-03 03:20:12.020: W/System.err(875): at android.app.ActivityThread.main(ActivityThread.java:5041)
    07-03 03:20:12.020: W/System.err(875): at java.lang.reflect.Method.invokeNative(Native Method)
    07-03 03:20:12.020: W/System.err(875): at java.lang.reflect.Method.invoke(Method.java:511)
    07-03 03:20:12.020: W/System.err(875): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    07-03 03:20:12.030: W/System.err(875): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    07-03 03:20:12.030: W/System.err(875): at dalvik.system.NativeStart.main(Native Method)
    07-03 03:20:12.030: W/System.err(875): Caused by: java.net.UnknownHostException: Unable to resolve host “www.itcuties.com”: No address associated with hostname
    07-03 03:20:12.030: W/System.err(875): at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
    07-03 03:20:12.040: W/System.err(875): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    07-03 03:20:12.040: W/System.err(875): at java.net.InetAddress.getAllByName(InetAddress.java:214)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpConnection.(HttpConnection.java:70)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpConnection.(HttpConnection.java:50)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
    07-03 03:20:12.040: W/System.err(875): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
    07-03 03:20:12.050: W/System.err(875): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
    07-03 03:20:12.050: W/System.err(875): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
    07-03 03:20:12.050: W/System.err(875): at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
    07-03 03:20:12.050: W/System.err(875): … 19 more
    07-03 03:20:12.050: W/System.err(875): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
    07-03 03:20:12.060: W/System.err(875): at libcore.io.Posix.getaddrinfo(Native Method)
    07-03 03:20:12.060: W/System.err(875): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:59)
    07-03 03:20:12.060: W/System.err(875): at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
    07-03 03:20:12.060: W/System.err(875): … 33 more

    Reply
    • itcuties says:

      Hello,
      this is strange, are you able to open “http://www.itcuties.com/feed” or “http://www.itcuties.com” in your emulator’s browser?

      Cheers,
      itcuties

      Reply
      • PC says:

        Hi,

        I am not able to open either of the urls on the emulator. In fact I’m not able to open any website.

        So I guess the problem is with my emulator. Please help me out set up the emulator.


        Thanks

        Reply
        • itcuties says:

          Hello,
          Please check if your system firewall doesn’t block the emulator process connections. Just disable your firewall for a minute and try to run the application.
          Can you post your virtual device settings?

          Take care,
          itcuties

          Reply
  56. Nora says:

    Hello,I am using the same code described in this video
    but when I running the program it is give me this error :Couldn’t open http://www.itcuties.com/feed/
    but on my browser this linke will be open
    I do not know what is the problem,please help me
    Thank you ^_^

    Reply
    • itcuties says:

      Hello Nora,
      This is because you are running this code on an Android 4+ emulator device. If you run it on Android 2 it will work 
      This code has over an 1,5 years and a lot has changed since then, and one thing that affects this code especially – all network communication needs to be done in a separate thread using AsyncTask. Take a look here – http://www.itcuties.com/android/android-asynctask-rss-reader/.

      Have a nice day,
      itcuties

      Reply
  57. Hyder says:

    I’m too facing the error “couldn’t open http://-url-” But when I run your project it opens perfectly.

    I read out comments many people are facing the same error I suggest you can pin its solution on the top or after the tutorial as a note. I may help people like me :)

    Reply
  58. mas93 says:

    hi.where can i add my info in code? i must write my own codes instead of blue codes right? but i cant understand.. here’s my own info : title: mfta link: mfta.com how can i this info tu source code? tnx

    Reply
  59. Janice says:

    Heloo ITCUTIES, I really appreciate this, but I tried and its not working in my code. I was using the Multicategory rss reader. I think the problem is the ATOM FEED URL. Im USING RSS xml URL. Is there’s a difference?

    Reply
  60. Rasmus Jakobsen says:

    Hi ITCUTIES,

    First of all, thanks for the tutorial!
    I’m having an odd problem with this RSS parser, as for some articles it will not read the entire content, but stops after 467 characters, even though it hasn’t reached the ending tag..
    This is an example of some content I’m trying to read:

    <![CDATA[Der har efterhånden været en del episoder med kidnapninger af hunde, som politiet har beslaglagt efter den kontroversielle hundelov. Den mest omtalte sag var da den ellers dødsdømte schæferhund Thor blev kidnappet af en politibetjent.Natten til søndag den 18. august 2013 blev der igen kidnappet beslaglagte hunde. Denne gang fra et dyreinternatet på Islevdalvej i København. Københavns Vestegns Politi efterforsker sagen, og leder efter 10 forsvundne hunde. Blandt hundene er en såkaldt muskelhund, en schæferhund samt en hunhund med syv blandingshvalpe.Fælles for alle hundene er, at de er beslaglagt af politiet i forbindelse med igangværende undersøgelser om skambidning eller racebestemmelse efter hundelovens regler. En racebestemmelse kan efter gældende dansk lovgivning medføre aflivning, hvis hunden vurderes til at indeholde en forbudt hunderace.Det er ikke længere tid siden end natten til fredag den 9. august, at der også blev kidnappet en anden beslaglagt hund d fra internatet. Hunden var beslaglagt i forbindelse med en sag om skambidning. De to sager har medført, at internatet ikke længere ønsker at modtage hunde fra politiet, og politiet derfor skal finde andre placeringsmuligheder imens sager om skambidning og ulovlige hunderacer undersøges.Læs mere om sagen på Ekstrabladet herThe post Beslaglagte hunde kidnappet fra internat appeared first on Dogsuniverse.dk.]]>
    Since this happens every time for this article, I suspect the reader for having an upper limit as to how many characters it is capable of storing at a given time. Everytime I run it, it stops at this exact location:
    ” Islevdalvej i København. Københavns Vestegns P” – as you can see, it was supposed to continue with:
    ” Islevdalvej i København. Københavns Vestegns Politi efterforsker sagen, og…” and so on.
    I have a hard time thinking it’s the fault of my phone, as I have an Asus Padfone2, which should be more than capable of handling more than 467 characters in memory :)

    Kind regards,
    Rasmus M. J. Jakobsen

    Reply
    • itcuties says:

      Hello, hello :)
      This is due the Internet connection. You need to check out our latest tutorial – http://www.itcuties.com/android/story-of-coding-itcutiesapp-for-android-parse-atom-modify-html-input-custom-listview-splash-screen-load-data-in-background/ where we have summarized our topics discussed in the past by publishing an app. Take a look at the parsing ATOM part – http://www.itcuties.com/android/story-of-coding-itcutiesapp-for-android-parse-atom-modify-html-input-custom-listview-splash-screen-load-data-in-background/#parse-rss-atom-data. ATOM has a different structure that the RSS channel you are trying to parse but the important thing here is that we are using the StringBuffer to read tag contents since the character method can run multiple times for the same tag (remember that we are parsing stream :))

      Reply
      • Rasmus Jakobsen says:

        Thanks for the fast reply.
        I see that you are always mentioning the feed as ATOM. Does this mean that I won’t be able to use this reader for regular RSS?
        I have the source available as both regular RSS and ATOM – what are the diffenrences? :)

        Reply
        • Rasmus Jakobsen says:

          Just a follow-up.
          I’ve taken a look at your RssPArseHandler from the 1st link you posted, and tried to implement it – thus using the StringBuffer you’ve provided. This results in some sort of Buffer Overflow exception (I can’t get a clear error through debugging), but I’ve been able to conclude that it happens during the currentTitleSb.append function.

          Here’s the code of my ParseHandler.

          public void startElement(String uri, String localName, String qName,
          			Attributes attributes) throws SAXException {
          		if ("item".equals(qName)) {
          			m_currentRssItem = new Article();
          		} else if ("title".equals(qName)) {
          			m_parsingTitle = true;
          		} else if ("link".equals(qName)) {
          			m_parsingLink = true;
          		} else if ("category".equals(qName)) {
          			m_parsingCategory = true;
          		} else if ("content:encoded".equals(qName)) {
          			m_parsingContents = true;
          		} else if ("pubDate".equals(qName)) {
          			m_parsingDate = true;
          		}
          	}
          
          	// The EndElement method adds the current Article to the list when a closing
          	// item tag is processed. It sets appropriate indicators to false - when
          	// title and link closing tags are processed
          	@Override
          	public void endElement(String uri, String localName, String qName)
          			throws SAXException {
          		if ("item".equals(qName)) {
          			m_rssItems.add(m_currentRssItem);
          			m_currentRssItem = null;
          		} else if ("title".equals(qName)) {
          			m_parsingTitle = false;
          			if(m_currentRssItem != null)
          				m_currentRssItem.setM_subject(m_currentTitleSb.toString());
          		} else if ("link".equals(qName)) {
          			m_parsingLink = false;
          		} else if ("category".equals(qName)) {
          			m_parsingCategory = false;
          		} else if ("content:encoded".equals(qName)) {
          			m_parsingContents = false;
          			if(m_currentRssItem != null)
          				m_currentRssItem.setM_content(m_currentTitleSb.toString());
          		} else if ("pubDate".equals(qName)) {
          			m_parsingDate = false;
          		}
          	}
          
          	// Characters method fills current Article object with data when tags are
          	// being processed
          	@Override
          	public void characters(char[] ch, int start, int length)
          			throws SAXException {
          		if (m_parsingTitle) {
          			if (m_currentRssItem != null)
          			{
          				//m_currentRssItem.setM_subject(new String(ch, start, length));
          				//m_currentTitleSb.append(new String(ch, start, length));
          				m_currentTitleSb.append(ch);
          			}
          		} else if (m_parsingLink) {
          			if (m_currentRssItem != null) {
          				m_currentRssItem.setM_link(new String(ch, start, length));
          			}
          		} else if (m_parsingCategory) {
          			if (m_currentRssItem != null) {
          				if(!new String(ch, start, length).equals("Artikler")){
          					m_currentRssItem.setM_category(new String(ch, start, length));
          				}
          			}
          		} else if (m_parsingContents) {
          			if (m_currentRssItem != null) {
          				String content = new String(ch, start, length);
          //				m_currentRssItem.setM_content(content);
          				//m_currentContentSb.append(new String(ch, start, length));
          				m_currentContentSb.append(ch);
          			}
          		} else if (m_parsingDate) {
          			if (m_currentRssItem != null) {
          				m_currentRssItem.setM_date(new String(ch, start, length));
          			}
          		}
          	}
          

          As you can see, I’ve tried using both the append(StringBuffer) and append(char[]) – neither of them work and both produce an instant crash when trying to load the articles. At this point, I’m clueless as to why I would receive a buffer overflow exception, as the articles really aren’t that long (as you can see from the OP) and any suggestions would be of great help :)

          Reply
  61. gourav says:

    Hi ,
    I have a problem , and it’s not problem in the same time !
    when I run the pro. nothing appear to me , the screen become black and nothing appear !
    and i want .
    when i click on list item, feed appear in Webview.

    Reply
  62. Younten Jamtsho says:

    How do you use with fragment? I have having trouble to when i use fragment.

    Reply
    • itcuties says:

      What problems do you have? You can describe your case and attach your code at http://www.itcuties.com/answers/.

      Reply
      • ictbhutan says:

        Main Activity

        package bt.yj.btnews;
        
        import android.app.ActionBar;
        import android.app.ActionBar.Tab;
        import android.app.Activity;
        import android.os.Bundle;
        
        
        public class MainActivity extends Activity {
        
            //declare Tab variable
            ActionBar.Tab tab;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
        
                // create actionbar
                ActionBar actionBar = getActionBar();
                //Hide actionbar
                actionBar.setDisplayShowHomeEnabled(true);
                //hide actionbar title
                actionBar.setDisplayShowTitleEnabled(true);
                // create actionbar tabs
                actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                // Create first Tab
                tab = actionBar.newTab().setTabListener(new Kuensel());
                // Create your own custom icon
                //tab.setIcon(R.drawable.tab1);
                tab.setText(R.string.KO);
                actionBar.addTab(tab);
                // Create Second Tab
                tab = actionBar.newTab().setTabListener(new BBS());
                // Set Tab Title
                tab.setText(R.string.BBS);
                actionBar.addTab(tab);
                // Create Second Tab
                tab = actionBar.newTab().setTabListener(new BO());
                // Set Tab Title
                tab.setText(R.string.BO);
                actionBar.addTab(tab);
                // Create Second Tab
                tab = actionBar.newTab().setTabListener(new tb());
                // Set Tab Title
                tab.setText(R.string.TB);
                actionBar.addTab(tab);
            }
        
        }
        

        Another Activity

        package bt.yj.btnews;
        
        import android.app.ActionBar;
        import android.app.Fragment;
        import android.app.FragmentTransaction;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
        
        
        public class BBS extends Fragment implements ActionBar.TabListener {
            private Fragment bbsFragment;
        
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                // Get the view
                getActivity().setContentView(R.layout.layout_bbs);
        
        
            }
        
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View MView = inflater.inflate(R.layout.layout_bbs, container, false);
        
                try {
                    RSSReader rssReader = new RSSReader("http://www.bbs.bt/news/?feed=rss2&quot;);
                    ListView Items = (ListView)MView.findViewById(R.id.listViewBBS);
                    /*ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, rssReader.getItems());*/
                    ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, rssReader.getItems());
                    Items.setAdapter(adapter);
                    Items.setOnItemClickListener(new ListListener(rssReader.getItems(), getActivity()));
                } catch (Exception e) {
                    Log.e("BTNews", e.getMessage());
                }
        
                return MView;
            }
        
            public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub
                bbsFragment = new BBS();
                ft.add(android.R.id.content, bbsFragment);
                ft.attach(bbsFragment);
            }
        
            public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub
                // Remove fragment1.xml layout
                ft.remove(bbsFragment);
            }
        
            public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
                // TODO Auto-generated method stub
        
            }
        }
        
        Reply
  63. gourav says:

    Hi ,
    I have a problem , and it’s not problem in the same time !
    when I run the pro. nothing appear to me , the screen become black and nothing appear !
    and i want .
    when i click on list item, feed appear in Webview.

    Reply
  64. PRS says:

    Hi,
    Thanks for the Post.
    I’m new to Android and I want to know can I get notification when the RSS Feed just updated ?

    Reply
  65. Mahmut says:

    Hi
    I want use this application together with my wordpress page
    but
    I can’t connect with my php page , for this reason , Can you share
    (http://www.itcuties.com/wp-atom.php) (wp-atom.php)
    or
    can you show one example php or xml page to me
    for connect ?
    or
    How I should do set my wordpress for this application ?
    please help
    thanks for answer

    Reply
  66. r.z says:

    thank’s for your tutorial. I had a question…
    How can I do to save last feeds in the application I mean when I close it and return to it, last blog post show to me without internet?
    (sorry for my bad English…)

    Reply
  67. Younten Jamtsho says:

    Sometime I get feeds with empty title. So how do i check for such empty title and not list them in the list view?

    Reply
  68. akshay bhoendie says:

    Nice tutorial, i have a problem .
    well i followed the each instruction step by step according to the tutorial,
    but now when i test the app on my mobile it comes blank, nothing. Do you know where i made a mistake, i’m a beginner.
    please can you help?

    Reply
  69. Kroshandowski says:

    Hi.Good tutorial, code work. I have question. How to make opening link in WebView, after cliking in ListView? Just news opened with a standard browser.

    Reply
  70. Dion says:

    Hi, when ever I parse the data and display it on screen I get a list of strange characters
    like so:
    com.itcuties.android.reader.data.RssItem@b114c1f8

    I am new at Java so I assume this is pointing to a memory reference. How do I correct it?

    Reply
    • itcuties says:

      Hello, these strange characters are the RssItem class default representation of an object. You are missing the toString method in your RssItem class.
      Here is the code:

      public String toString() {
           return title;
      }
      
      Reply
  71. Viktor says:

    Hi itcuties,
    first of all thank you for this great tutorial – it help me alot!
    But i still have a problem, if i start my app on the emulator
    i receive this as result
    http://imgur.com/YoyXJeq
    no titel ect.
    hope u can help me to fix it.
    I did the code step by step.
    and allready compare it to yours, but i cant find the mistake :(
    PS: “SchwarzesBrett” is the project name similar to your “reader”

    Reply
  72. Olivia says:

    Hello,

    By using your code I get a problem with the titles of some articles. When the title contains a special character ( in the html source code of the rss feed link) the title is cut, only the part of the title after this character is displayed in the application.

    For example : There is one article named Let’s go! in the feed, but in the html source code of the feed it is Let’s go! . In the application only s go! is displayed as the title of the article.

    Where in the app could I modify the ’ symbol or deal with it ?

    Thank you in advance.

    Reply
    • Olivia says:

      Sorry I am making so much mistakes today.
      Here is the right piece of code that solved my problem :

      In characters method of RssParseHandler.java I changed this :

      if (parsingTitle){
          if (currentItem != null) {
              currentItem.setTitle(new String(ch, start, length));
          }
      

      to

      if (parsingTitle){
          if (currentItem != null) {
              if (currentItem.getTitle() == null){
                  currentItem.setTitle(new String(ch, start, length))
              }else {
                  currentItem.setTitle(currentItem.getTitle()+new String(ch, start, length));
              }
          }
      
      Reply
  73. john says:

    Hello,

    I have followed your tutorial closely and was wondering if you could help me. I would like to be able to filter the rss feed to only display items from a specific day.

    John.

    Reply
  74. shekhar says:

    Hai
    I have a problem on rss feed.I want to display images and title in a row of list view. Please send the total code of rss feed with images.

    Reply
  75. Sheldon says:

    Hi, thanks for the tutorials.

    I also have problems with images. All i can see are grey imageViews…
    i added my code on stackoverflow, here’s the link
    https://stackoverflow.com/questions/19178279/how-to-add-images-to-listview-rss-feed?rq=1

    thank you in advance

    Reply
  76. Sheldon says:

    how can i get the content of an rssItem and show it in the same application instead of opening the link in the browser?

    Reply
  77. Zeter Lee says:

    Hello,

    Thanks for posting and it helps a lot to me. One thing that i really want to add to this code is adding a Image [like thumbnail] in RSS which will appear on left side of TEXT [Title, description...]. But problem is, hard to get Image URL from XML file.

    My app getting feeds from several XML and image url of some feed page is included in node named “content:encoded” and some page includes this url in description node. And also those node includes not only IMAGE URL, also several contents like below,

    [XML was here :)]

    Here my question is,
    1. how to take only image URL.
    2. Like i mentioned above, image URL is included in different node from different page. Any idea for good design?

    Thank you

    Reply
  78. anant says:

    How to add application lifecycle in to this code.??? Please mention in the updated app;ication code where you have arranged the working in main activity class with async task

    Reply
  79. Although says:

    Hi guys!

    There seems to be a problem with the getItems() method in the RssReader class.
    This method must return a result of type List
    But the thing is that if returned handler.getItems(), you get the following message: The method getItems() is undefined for the type RssParseHandler.

    Reply
  80. Bao lam says:

    Hi, i ran the application but it gave me an empty screen, any idea why ?

    Reply
  81. Rony says:

    The window shown only blank(no data) with Consoles:

    [2014-06-13 16:00:22 - ddmlib] Broken pipe
    java.io.IOException: Broken pipe
    	at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
    	at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
    	at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    	at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    	at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:466)
    	at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
    	at com.android.ddmlib.Client.sendAndConsume(Client.java:642)
    	at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:348)
    	at com.android.ddmlib.Client.requestAllocationStatus(Client.java:488)
    	at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:835)
    	at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:803)
    	at com.android.ddmlib.DeviceMonitor.processIncomingJdwpData(DeviceMonitor.java:763)
    	at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:652)
    	at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:44)
    	at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:580)
    
    Reply
  82. Cosmin says:

    Hello itcuties,

    Thank you so much for this wonderful tutorial.
    I have a short question: I have some feeds that are not opening and I’m guessing that this issue is caused by the fact that the rss feed is not available on the mobile version of the site.
    Please check: http://www.antena3.ro/rss
    Opening this URL from the browser it will generate a “Not Found” error because it will redirect me to m.antena3.ro/rss which is not available.
    It is my guess that your class will doing the same and the feed will not be available in the app
    Is there a way to fix this?

    Many thanks,
    Cosmin

    Reply
    • itcuties says:

      The address you have provided looks about right… Did you managed to resolve the issue?

      Reply
      • Cosmin says:

        Yeah, the problem is that they don’t have a mobile version of the feed and when trying to access http://www.antena3.ro/rss it redirected me to m.antena3.ro/rss which was invalid.
        I had to save the .xml locally using a ‘desktop’ User-Agent and parsing it from there afterwards
        Thanks again

        Reply
  83. Pkmmte Xeleon says:

    Alternatively, you can use a third party RSS library such as this one:
    https://github.com/Pkmmte/PkRSS

    It handles all RSS code via a fluent API and is very customizable.

    // Load a URL
    PkRSS.with(this).load(url).async();
    
    // Get the feed
    List articleList = PkRSS.with(this).get(url);
    

    There are also callbacks, synchronous calls, a favorite database, marked as read, pagination support, searching, custom parsers/downloaders, and more.

    Reply
  84. Habib says:

    Hello There,

    I am a bit new to android development and I found this tutorial to be awesome!. I am having a problem trying to add a refresh button that will actually refresh the page and ‘re load’ the rss page.

    The only thing I have been able to do is get the refresh button to show up on the correct page and when its pressed it displays refresh clicked, as is shown in the code below.

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.action_refresh:
    Toast.makeText(this, “Refresh clicked”, Toast.LENGTH_SHORT).show();
    return true;
    default:
    return super.onOptionsItemSelected(item);
    }
    }

    If possible would you please be able to help with implementing a refresh button.

    Thank you so much for all your help and again, your tutorials are awesome :)
    Habib

    Reply
  85. StudioDamage says:

    Hi.

    I do everything what is in this tutorial, but when i start application it say Couldn’t open http://www.itcuties.com/feed/.

    I tester it on Android 2.2 in emulator and phisical device with Android 4.1.2

    Reply
  86. ghanshyam says:

    How to parse utf-8 or font from assets typeface so multi language support In list view

    Reply
  87. Pramod Gupta says:

    Hi i want to know about this particular method

    public String toString() {
    		return title;
    	}
    

    what is use of the method in RssItem. class.
    When this method is called ?
    Thank you.

    Reply
  88. Amit Kumar says:
    public List getItems() throws Exception {
    	        // At first we need to get an SAX Parser Factory object
    	        SAXParserFactory factory = SAXParserFactory.newInstance();
    	        // Using factory we create a new SAX Parser instance
    	        SAXParser saxParser = factory.newSAXParser();
    	        // We need the SAX parser handler object
    	        RssParseHandle handler = new RssParseHandle();
    	        // We call the method parsing our RSS Feed
    	        saxParser.parse(rssUrl, handler); // saying change type of handler to handlerbase
    	        // The result of the parsing process is being stored in the handler object
    	        return handler.getItems();
    	    }
    // when change the handler
    

    i am beginner in android

    Reply
  89. art says:

    Hello

    and
    currentItem.setLink(new String(ch, start, length)
    not returned link completly
    i think because of &
    the link i used contain & character

    Reply
  90. vivek says:

    hello thanks for the code
    but when i download code for eclipse from your given link and open in my eclipse it gives me error
    actually in my eclipse code is not visible it shows me all empty files
    please help..

    Reply
  91. Genaro says:

    The tutorial uses SAX parser and includes a complete Android project that accesses an RSS feed and then displays the feed in a list view.

    Reply
  92. Ann says:

    Hi, first thanks for the tutorial.

    I have an issue if you don’t mind answering a beginner’s question. I want to move onItemClick from ListListener.java to RssChannelActivity, so that I could add other clicking options. I am able to implement clicking and other options, but I could not get the link to open in a browser. Here’s the sample code:

    inside onPostExecute(List result)

      itcItems.setOnItemClickListener(itemClickListener);
    

    outside onPostExecute:

    OnItemClickListener itemClickListener = new OnItemClickListener() {
    	@Override
        public void onItemClick(AdapterView parent, View view, int pos, long id) {
    
    
                            Intent i = new Intent(Intent.ACTION_VIEW);
     			i.setData(Uri.parse(listItems.get(pos).getLink()));
      			startActivity(i);
    
    	}
    

    Error

    08-08 08:58:42.780: E/AndroidRuntime(26909): Caused by: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.RSS/com.example.RSSReader.RssChannelActivity}: java.lang.InstantiationException: can’t instantiate class com.example.RSSReader.RssChannelActivity; no empty constructor

    What does this mean? How is possible that I can implement item click, popping up a toast, but not open the link?

    Reply
  93. Muhammad says:

    i have copy pasted the above all files code though my project is working but nothing is showing on the project white screen only, can some one please tell me….please

    Reply
  94. AAYUSH BEDI says:

    I am using fragments instead of activity for the RSSFeed for my application. I am facing problem in the postExecute method as i have declared the local variable of Fragment type.

    here is my code :

    public class HomeFragment extends Fragment {
        // TODO: Rename parameter arguments, choose names that match
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        private static final String ARG_PARAM1 = "param1";
        private static final String ARG_PARAM2 = "param2";
    
        // TODO: Rename and change types of parameters
        private String mParam1;
        private String mParam2;
    
        private OnFragmentInteractionListener mListener;
    
        private HomeFragment local;
         /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment HomeFragment.
         */
        // TODO: Rename and change types and number of parameters
        public static HomeFragment newInstance(String param1, String param2) {
            HomeFragment fragment = new HomeFragment();
            Bundle args = new Bundle();
            args.putString(ARG_PARAM1, param1);
            args.putString(ARG_PARAM2, param2);
            fragment.setArguments(args);
            return fragment;
        }
    
        public HomeFragment() {
            // Required empty public constructor
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                mParam1 = getArguments().getString(ARG_PARAM1);
                mParam2 = getArguments().getString(ARG_PARAM2);
            }
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            // Set reference to this activity
            local = this;
    
            GetRSSDataTask task = new GetRSSDataTask();
    
            // Start download RSS task
            task.execute("http://www.itcuties.com/feed/&quot;);
    
            // Debug the thread name
            Log.d("ITCRssReader", Thread.currentThread().getName());
            return inflater.inflate(R.layout.fragment_home, container, false);
        }
    
        private class GetRSSDataTask extends AsyncTask&lt;String, Void, List&gt; {
            @Override
            protected List doInBackground(String... urls) {
    
                // Debug the task thread name
                Log.d("ITCRssReader", Thread.currentThread().getName());
    
                try {
                    // Create RSS reader
                    RssReader rssReader = new RssReader(urls[0]);
    
                    // Parse RSS, get items
                    return rssReader.getItems();
    
                } catch (Exception e) {
                    Log.e("ITCRssReader", e.getMessage());
                }
    
                return null;
            }
    
            @Override
            protected void onPostExecute(List result) {
    
                // Get a ListView from main view
                ListView itcItems = (ListView)findViewById(R.id.ListMainView);// error: cannot resolve method findViewById
    
                // Create a list adapter
                ArrayAdapter adapter = new ArrayAdapter(local,android.R.layout.simple_list_item_1, result); // error : Cannot resolve constructor ArrayAdapter(fragment,int,java.util.list)
                // Set list adapter for the ListView
                itcItems.setAdapter(adapter);
    
                // Set list view item click listener
                itcItems.setOnItemClickListener(new ListListener(result, local));  // error : List,activity cannot be applied to List,fragment
            }
        }
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
    
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
    
        }
    
    
        /**
         * This interface must be implemented by activities that contain this
         * fragment to allow an interaction in this fragment to be communicated
         * to the activity and potentially other fragments contained in that
         * activity.
         * 
         * See the Android Training lesson <a href="*" rel="nofollow">Communicating with Other Fragments</a> for more information.
         */
        public interface OnFragmentInteractionListener {
            // TODO: Update argument type and name
          //  public void onFragmentInteraction(Uri uri);
        }
    
    }
    
    Reply
  95. Muhammad Salim says:

    I want to Show URL in WebView Please tell me how can I show it??????

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>