Android AsyncTask RSS Reader

Today we have a little modification of our RSS Reader code that we have introduced in the How to write Android RSS parser tutorial. This modification uses AsyncTask to download RSS data in a separate thread. We have only modified the ITCutiesReaderAppActivity class code. Here it is.

ITCutiesReaderAppActivity

package com.itcuties.android.reader;

import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
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.
 * 
 * Update: Downloading RSS data in an async task 
 * 
 * @author ITCuties
 *
 */
public class ITCutiesReaderAppActivity extends Activity {
	
	// A reference to the local object
	private ITCutiesReaderAppActivity local;
	
	/** 
	 * This method creates main application view
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set view
		setContentView(R.layout.main);

		// Set reference to this activity
		local = this;
		
		GetRSSDataTask task = new GetRSSDataTask();
		
		// Start download RSS task
		task.execute("http://www.itcuties.com/feed/");
		
		// Debug the thread name
		Log.d("ITCRssReader", Thread.currentThread().getName());
	}
	
	private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
		@Override
		protected List<RssItem> 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<RssItem> result) {
			
			// Get a ListView from main view
			ListView itcItems = (ListView) findViewById(R.id.listMainView);
						
			// Create a list adapter
			ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1, result);
			// Set list adapter for the ListView
			itcItems.setAdapter(adapter);
						
			// Set list view item click listener
			itcItems.setOnItemClickListener(new ListListener(result, local));
		}
	}	
}

In this code we start a task in the onCreate method. This task is implemented as a private GetRSSDataTask class which extends AsyncTask class. Task downloads RSS data in the doInBackground method. After download is done the doPostExecute method is called automatically. In this method we modify ListView by setting an ArrayAdapter and a OnItemClickListener the same way as before.

When you start the application it displays two messages in the log displaying running threads names. As you can see AsyncTask code is being run in a separate thread.

Android AsyncTask RSS Reader Output

Android AsyncTask RSS Reader Output

Download this sample code here.

This code is available on our GitHub repository as well.

77 Responses to "Android AsyncTask RSS Reader"

  1. Duke says:

    Hey, that helped me, thx :).
    Just a little comment:
    you may want to use a simple ProgressDialog and set it up in onPreExecute() (and make it disappear in your onPostExecute) in case rss parsing takes a little longer and the user won’t think his or her UI is frozen ;)

    Reply
  2. Carlo says:

    It doesn’t parse all the information if there are special characters like & in the XML

    Reply
  3. kuldeep says:

    hi i am developing app to read feeds from a url but i always see a blank screen .. i tried my best plss let me know the solution.. the link is given below..
    “http://www.ignou.ac.in/ignou/footer/rss”

    Reply
    • itcuties says:

      Hello Kuldeep,
      There is an encoding problem with your RSS channel. It contains some unparsable signs. What we did was downloading your XML, converted it to UTF-8 while changing the XML’s header to

      <?xml version="1.0"  encoding="UTF-8"?>
      

      and now it is works.

      It is available in our temporary location at http://download.itcuties.com/tmp-xml/test-rss.xml

      Have a nice day :)
      itcuties

      Reply
  4. Yousef says:

    I’m loading xml i’ m loading the content in TextView in html/text but the embedded image not showing in textview.How can I show the image.
    Also I want to get the comment of each Item in my rss I have the link of my comment rss but I don’t know how to loop through all of my comment and show them in correct way as publishername, date, email, comment.

    thanks if u can help

    Reply
  5. Yousef says:

    Thanks for reply below is the link for xml for comment:
    “http://www.gerishna.com/archives/16425#comments”

    I can show them in listView but I want to get them in order and all of them in one page.Now I am using listview selectable for each comment after click on user name it will go to next activity to show the description. I want all to be in list view row or gridview but line by line with Name, Date and description.

    I used WebView but it not works for API 2.2 and less it give me error. So I used textview for this task. When i use webview i can show images but in newer version.

    if it is possible to make another post for getting XML but showing on fragment instead of using activity.
    One more thing if you can teach on one post something like have newsreader :

    Row of News and Column of Category

    CATEGORY ROW CAN BE MOVE UP AND DOWN.
    NEWS ROW CAN BE MOVE LEFT AND RIGHT

    CATEGORY ONE
    NEWS1 | NEWS2 | NEWS3
    CATEGORY TWO
    NEWS1 | NEWS2 | NEWS3
    CATEGORY THREE
    NEWS1 | NEWS2 | NEWS3

    AFTER USER CLICK ON EACH NEWS IT SHOW IN OPPOSITE FRAGMENT LIKE WHICH IS AVAILABLE IN ECLIPSE FOR BIG SCREEN.SO IN THE RIGHT CORNER OF DESCRIPTION NEW WE CAN APPLY COMMENT SECTION AS CLICK IT WILL SHOW ANOTHER FRAGMENT FOR COMMENT OF SPECIFIC NEWS.

    I don’t want all of this project to be done I just want to get an idea of how to move layout and how to work with fragment like this project. for different screen and device.

    Thanks a lot.

    Reply
  6. Yousef says:

    I send the comment xml link in previous comment, let me know is it possible to send comment from my device through the XML.

    plz also teach on one post for sharing link to facebook, twitter and google +. In web available but the way your are teaching is more simple and straight.

    Thanks alot.

    Reply
    • itcuties says:

      Hello Yousef,
      Thanks for the tutorial idea – sharing post over Facebook, G+ and Twitter. We will have to think about it.
      As for posting comments. What’s the technology behind your web site. Does it provide any API (maybe REST API?) for interacting with it?

      Take care,
      itcuties

      Reply
  7. Jared says:

    Hi,

    How would I parse special characters in the feed?

    For example “Man of Steel [3D] (10–12PG)” will only display “12PG)” in the list view.

    Thank you

    Reply
    • itcuties says:

      Hello Jared,

      it’s a bug :) which we corrected in the Atom Feed tutorial. You need to use a StringBuffer (StringBuilder would be a better choice here!) object to append the tag content to it because sometimes the characters method is called multiple times reading some tag content. This is due the network speed. Take a look at the currentTitleSb attribute and how it is being filled with data – http://www.itcuties.com/android/atom-parser/#rss-atom-parse-handler. Have in mind that this code parses Atom feed which has different structure but you get the idea :)
      In case of any questions considering other cases you can ask them using our new ask&answer page – http://www.itcuties.com/answers :)

      Have a nice day,
      itcuties

      Reply
  8. yousef says:

    hi,
    I want app to pars the xml as soon as device connect to internet and show notification of getting data. Plz let me know what should i use or is there API for checking connection.

    Reply
    • itcuties says:

      Hello, you can implement this using Android Service API. Service is a component that runs in background.Your service should check if it can connect to your RSS URL, download data and inform user about it in the notification bar.

      itcuties

      Reply
    • Yousef says:

      I solve the problem.
      here is the code I listen for anykind of connection and notify user with clickable notification to open APP

      public class ConnectivityReceiver extends BroadcastReceiver {
      	public static final String EXTRA_MESSAGE = null;
      	  NotificationManager mNotificationManager ;
      	  public static final int NOTIFICATION_ID = 1;
      	  int icon = R.drawable.ic_launcher;
      	  CharSequence tickerText = "tickertext here";
      	  long when = System.currentTimeMillis();
      	 
      	   String message=null;
      	 @Override
      	  public void onReceive( Context context, Intent intent )
      	  {
      		 mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
      		 message="http://www.gerishna.com/feed&quot;;
      		
      		 Notification notification = new Notification(icon, tickerText, when);
      		 CharSequence NotificationTitle = "title here ";
      		  CharSequence NotificationContent = "content here";
      		  Intent notificationIntent = new Intent(context, YourClass.class);
      		  notificationIntent.putExtra(EXTRA_MESSAGE, message);
      	      PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
      	   
      	      
      	    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
      	    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
      	   
      	    if ( activeNetInfo != null)
      	    {
      	    	   notification.setLatestEventInfo(context, NotificationTitle, NotificationContent, contentIntent);
      	 	      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      	 	    mNotificationManager.notify(NOTIFICATION_ID, notification);
      	
      	    }
      }
      }
      
      Reply
  9. yousef says:

    How can I add Load More Button to the list view to show more news?

    Reply
    • itcuties says:

      Hello,
      Adding a button is the easiest part. You can do it like this:

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical" >
      
          <ListView
              android:id="@+id/rssItemsList"
              android:layout_width="match_parent"
              android:layout_height="300dp" >
          </ListView>
      
          <Button
              android:id="@+id/loadMore"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Load more" />
      
      </LinearLayout>
      

      Are you able to provide XML files that contain partial RSS data which you want to load while the button is pressed? Or maybe the app should load all the items available in the RSS feed and split them into parts that will be loaded when the button is pressed. What’s your case?

      Take care,
      itcuties

      Reply
  10. Nora says:

    Hello,I am using this code in my application but it’s give me this error
    java.lang.RuntimeException: An error occured while executing doInBackground()

    what is the solution??

    07-16 08:47:59.420: D/AbsListView(20157): Get MotionRecognitionManager
    07-16 08:47:59.425: D/ITCRssReader(20157): main
    07-16 08:47:59.425: D/ITCRssReader(20157): AsyncTask #1
    07-16 08:47:59.535: D/libEGL(20157): loaded /system/lib/egl/libEGL_mali.so
    07-16 08:47:59.550: D/libEGL(20157): loaded /system/lib/egl/libGLESv1_CM_mali.so
    07-16 08:47:59.550: D/libEGL(20157): loaded /system/lib/egl/libGLESv2_mali.so
    07-16 08:47:59.555: D/(20157): Device driver API match
    07-16 08:47:59.555: D/(20157): Device driver API version: 10
    07-16 08:47:59.555: D/(20157): User space API version: 10 
    07-16 08:47:59.555: D/(20157): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012 
    07-16 08:47:59.615: D/OpenGLRenderer(20157): Enabling debug mode 0
    07-16 08:47:59.840: W/dalvikvm(20157): threadid=11: thread exiting with uncaught exception (group=0x40f5d2a0)
    07-16 08:47:59.855: E/AndroidRuntime(20157): FATAL EXCEPTION: AsyncTask #1
    07-16 08:47:59.855: E/AndroidRuntime(20157): java.lang.RuntimeException: An error occured while executing doInBackground()
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at android.os.AsyncTask$3.done(AsyncTask.java:299)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.lang.Thread.run(Thread.java:856)
    07-16 08:47:59.855: E/AndroidRuntime(20157): Caused by: java.lang.NullPointerException: println needs a message
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at android.util.Log.println_native(Native Method)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at android.util.Log.e(Log.java:297)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at com.example.newsrss.MainActivity$GetRSSDataTask.doInBackground(MainActivity.java:66)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at com.example.newsrss.MainActivity$GetRSSDataTask.doInBackground(MainActivity.java:1)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at android.os.AsyncTask$2.call(AsyncTask.java:287)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    07-16 08:47:59.855: E/AndroidRuntime(20157): 	... 5 more
    07-16 08:48:09.130: D/AbsListView(20157): Get MotionRecognitionManager
    07-16 08:48:09.135: D/ITCRssReader(20157): main
    07-16 08:48:09.135: D/ITCRssReader(20157): AsyncTask #3
    07-16 08:48:09.610: W/dalvikvm(20157): threadid=13: thread exiting with uncaught exception (group=0x40f5d2a0)
    07-16 08:48:09.610: I/Process(20157): Sending signal. PID: 20157 SIG: 9
    07-16 08:53:43.400: I/Process(20670): Sending signal. PID: 20670 SIG: 9
    07-16 08:58:27.800: D/AbsListView(21249): Get MotionRecognitionManager
    07-16 08:58:27.810: D/ITCRssReader(21249): main
    07-16 08:58:27.810: D/ITCRssReader(21249): AsyncTask #1
    07-16 08:58:27.895: D/libEGL(21249): loaded /system/lib/egl/libEGL_mali.so
    07-16 08:58:27.905: D/libEGL(21249): loaded /system/lib/egl/libGLESv1_CM_mali.so
    07-16 08:58:27.910: D/libEGL(21249): loaded /system/lib/egl/libGLESv2_mali.so
    07-16 08:58:27.910: D/(21249): Device driver API match
    07-16 08:58:27.910: D/(21249): Device driver API version: 10
    07-16 08:58:27.910: D/(21249): User space API version: 10 
    07-16 08:58:27.910: D/(21249): mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012 
    07-16 08:58:27.965: D/OpenGLRenderer(21249): Enabling debug mode 0
    07-16 08:58:32.315: W/dalvikvm(21249): threadid=11: thread exiting with uncaught exception (group=0x40f5d2a0)
    07-16 08:58:32.345: E/AndroidRuntime(21249): FATAL EXCEPTION: AsyncTask #1
    07-16 08:58:32.345: E/AndroidRuntime(21249): java.lang.RuntimeException: An error occured while executing doInBackground()
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at android.os.AsyncTask$3.done(AsyncTask.java:299)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.lang.Thread.run(Thread.java:856)
    07-16 08:58:32.345: E/AndroidRuntime(21249): Caused by: java.lang.NullPointerException: println needs a message
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at android.util.Log.println_native(Native Method)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at android.util.Log.e(Log.java:297)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at com.example.newsrss.MainActivity$GetRSSDataTask.doInBackground(MainActivity.java:69)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at com.example.newsrss.MainActivity$GetRSSDataTask.doInBackground(MainActivity.java:1)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at android.os.AsyncTask$2.call(AsyncTask.java:287)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    07-16 08:58:32.345: E/AndroidRuntime(21249): 	... 5 more
    

    It is show me this errors

    Reply
  11. Coderz says:

    Can you please give an example of CustomAdapter in the same code ? Thanks in advance

    Reply
  12. Coderz says:

    Yeah, thanks, i have many such example. But as you are aware of your code, if you can modify and give us example it would be really helpfup

    Reply
  13. kamran says:

    hi thanks for your great tutorial i want to make a rss feed for http://www.zigil.ir the channel doesnt support utf-8 and i must do something to do the job can i somehow get the xml encode it and read from that somehow?
    if yes how?

    Reply
    • charlie says:

      Hello Kamran,
      you can convert each value you read from XML from your charset to UTF-8. This should do the trick.

      String newString = new String(oldString.getBytes("[YOUR-CHARSET-HERE]"), "UTF-8"));
      

      Cheers!
      Charlie

      Reply
  14. James G says:

    Great tutorial, helped me out massively with my app. Big question for me is, I want to send an intent to open my WebActivity.class so that when a user clicks on one of the rss items, it goes to that and opens in webview instead of another app.

    Many Thanks for any help
    Jim

    Reply
  15. Pradana says:

    please help me, I tried use feed from my blog “http://pradan-cuk.blogspot.com/feeds/posts/default”
    but that just show a blank display
    but if I try to display rss with widged on my blog it appears
    What should I do in order to appear in my application

    sorry for my bad english

    Reply
  16. Julian Nexus says:

    Hello, need to ask these questions

    1. What type of AVD did you use for this project?

    2. How do I get to retrieve & gather everyday top stories from all over the world?

    3. Do I need a database for this project? If so, what kind of database would you recommend?

    Thanks!

    Reply
  17. kamran says:

    hi when i see the rss adrese i dont see anything related to the photo i wrote an application based on your video which stores the news in sqlite but my question is how can i download the image for every news is it possible to use sax parser for doing this or i should use sth like jsoup
    my second question is that which way is better using jsoup or sax parser for writing rss?

    Reply
    • itcuties says:

      Hello,
      You can use this code to download images in your app.

      InputStream is = (InputStream) new URL(url).getContent();
      Drawable d = Drawable.createFromStream(is, null);
      is.close();
      

      As for the second question parsing XML is better done with the SAX parser. Actually we have not used JSoup to parse anything but HTML pages.

      Have a nice day,
      itcuties

      Reply
  18. kamran says:

    another question when i get the news it has dozens of like &hellip  how to remove them?
    currently i have

    currentItem.setDescription(f.replace("&nbsp;", " ")
    						.replace("&hellip;", " ").replace("&rdquo;", " ")
    						.replace("&ldquo;", " ").replace("&laquo;", " ")
    						.replace("&raquo;", " ").replace("&ndash;", " "));
    

    isnt there a better way?

    Reply
    • itcuties says:

      Hello again Kamran,
      the best way is to assure that the RSS feed you parse is properly coded and doesn’t contain any weird signs :)
      The code you show is a propper way of dealing with the problem.

      Cheers,
      itcuties

      Reply
  19. Reyo says:

    Hi, thank you for the tutorial. I have a bit of trouble here.

    I got an error when typing this code:

    RssReader rssReader = new RssReader(urls[0]);
    

    The error says: “Cannot instantiate the type RssReader”

    I am not instantiating an interface, an abstract nor a list, I don’t see why I have this error.

    It suppose to call this in RssReader class right?

    public RssReader(String rssUrl) {
    		this.rssUrl = rssUrl;
    	}
    

    if so, then it probably not calling it for some reason.

    Reply
  20. kamran says:

    hi again this is the rss xml node i want to parse:

    http://www.zigil.ir/rss/

    as you see it has a media:thumbnail url node which has the link of the image src and i want to get this link while parsing and it is a subnode of desc so how should i get it in your way currently i have this

    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 ("description".equals(qName)) {
    			parsingDes = true;
    		}else if("media:thumbnail".equals(qName)){
    			parsingImage=true;
    		}
    	}
    

    and this

    @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;
    		} else if ("description".equals(qName)){
    			parsingDes = false;
    	}else if("media:thumbnail".equals(qName))
    		parsingImage=false;
    
    	}
    

    which ofcourse doesnt get the url how can i get it?

    Reply
    • itcuties says:

      In your startElement method in the media:thumbnail if block you can read the URL with this code:

      attributes.getValue("url");
      
      Reply
      • kamran says:

        sorry i didn’t understand what you mean
        these are my if blocks related to the image
        can you please tell me exactly what should i write for this problem in my startelement end and character?

        Reply
        • kamran says:

          well you mean i create a new global variable like

          string img;
          

          then in startelement writing this

          }else if("media:thumbnail".equals(qName)){
          			img=attributes.getValue("url");
          			parsingImage=true;
          			
          		}
          

          in endelement writing this

          else if ("media:thumbnail".equals(qName)){
          		parsingImage=true;
          

          and in character writing this

          }else if(parsingImage){
          			if(currentItem!=null){
          				currentItem.setImagelink(img);
          				parsingImage=false;
          			}
          		}
          

          am i right?

          Reply
  21. Nikolas says:

    Hello, need to ask these questions

    i have a problem with my rss feed.

    the Rss_ParseHandler works just fine and it adds items in Arraylist but when the onPostExecute returned result NULL

    Reply
  22. Viktor says:

    Is there a reason I’m getting only one RSS item? This is my code:

    @SuppressLint({ "NewApi", "ShowToast" })
    public class ArticleFragment extends Fragment {
    	
    	public ArticleFragment(){}
    	public View v;
         
    
    	@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
     
            	View rootView = inflater.inflate(R.layout.fragment_article, container, false);
            	v = rootView;
                 
                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 rootView;
        }
    	class GetRSSDataTask extends AsyncTask&lt;String, Void, List &gt; {
    	    @Override
    	    public 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) v.findViewById(R.id.listMainView);
                             
                // Create a list adapter
                ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, result);
                // Set list adapter for the ListView
                itcItems.setAdapter(adapter);
                
                             
                // Set list view item click listener
                itcItems.setOnItemClickListener(new ListListener(result, getActivity()));
            }
    	} 
    }
    

    And my xml:
    [missing XML]
    Please help!

    Reply
  23. Viktor says:

    Hi Cuties,
    my RSS Feed Reader works fine on “normal” rss feeds, BUT the rss i wanna read requires a authentification with username and password on the page ( NOT extra Window) its part of the page and if u login you can see the rss feed immediately.
    I search and read different things about authentification, but the most solutions are made with 3th party like rome or apache.
    Is there any opportunity to solve it without 3th party?
    And where i should add it in this Code of your RSS Reader?!?!

    Looking forward hopefully
    Viktor

    Reply
    • itcuties says:

      Hey man! If there is a need to provide a login and a password in a login page (not a BASIC authentication window) you should check this page’s code for the action value of the form that takes credentials. You can send a login/password data using POST or GET requests – you have to see which one is used by analysing login page code. This way you can authenticate to your page. But still, you will have to maintain the HTTP session in your application. Let’s say you have been authenticated with the POST request, next you have to send the GET request to load the RSS data but this request is not authenticated if you don’t keep it in the same HTTP session as the previous one…

      You might find this link useful – http://www.itcuties.com/java/send-post-request/

      Reply
  24. kamran says:

    hi one more question when i get the rss and show them in the description i sometimes have something like 10 spaces and the description i use method trim to remove them but i still have them !!!
    of course it is not really common but every 15 news i get one how can i remove them?
    (the news is in persian not english)

    Reply
  25. Arjun says:

    Hi there ,
    I am using the Asynctask but do not get to run the app. I get the following error. I am wondering if you have any suggestion.

    Thanks

    03-22 14:19:21.380: D/ITCRssReader(1420): main
    03-22 14:19:21.390: D/ITCRssReader(1420): AsyncTask #2
    03-22 14:19:21.510: I/Choreographer(1420): Skipped 127 frames!  The application may be doing too much work on its main thread.
    03-22 14:19:21.630: I/Choreographer(1420): Skipped 113 frames!  The application may be doing too much work on its main thread.
    03-22 14:19:37.150: I/Choreographer(1420): Skipped 36 frames!  The application may be doing too much work on its main thread.
    03-22 14:19:37.580: I/Choreographer(1420): Skipped 347 frames!  The application may be doing too much work on its main thread.
    03-22 14:19:52.470: I/Choreographer(1420): Skipped 575 frames!  The application may be doing too much work on its main thread.
    
    Reply
  26. h2oman says:

    My list view is showing like this

    com.stoncreek.rssreaders.app.RssItems@b2e188f8
    com.stoncreek.rssreaders.app.RssItems@b2e182d8

    etc

    If i click on them it actually goes to the right page but the title is not coming through.

    I seem to me missing something.

    Reply
  27. jef says:

    Hi,

    When I load the app is says ‘unfortunately the app has stopped working’. The code I have used is exactly the code above…
    Is there anything I can do?

    Thanks in advance,

    Jef

    Reply
  28. jef says:

    Hi,

    Below is the copy and paste from the log cat.

    05-22 17:37:56.373: D/AndroidRuntime(1033): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
    05-22 17:38:02.603: D/AndroidRuntime(1049): CheckJNI is ON
    05-22 17:38:02.723: D/dalvikvm(1049): Trying to load lib libjavacore.so 0×0
    05-22 17:38:02.733: D/dalvikvm(1049): Added shared lib libjavacore.so 0×0
    05-22 17:38:02.763: D/dalvikvm(1049): Trying to load lib libnativehelper.so 0×0
    05-22 17:38:02.763: D/dalvikvm(1049): Added shared lib libnativehelper.so 0×0
    05-22 17:38:02.763: D/dalvikvm(1049): No JNI_OnLoad found in libnativehelper.so 0×0, skipping init
    05-22 17:38:03.033: D/dalvikvm(1049): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
    05-22 17:38:03.733: E/memtrack(1049): Couldn't load memtrack module (No such file or directory)
    05-22 17:38:03.733: E/android.os.Debug(1049): failed to load memtrack module: -2
    05-22 17:38:04.093: D/AndroidRuntime(1049): Calling main entry com.android.commands.am.Am
    05-22 17:38:04.183: I/ActivityManager(370): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0×10000000 cmp=com.test1/.Splash} from pid 1049
    05-22 17:38:04.273: E/gralloc_goldfish(49): gralloc_alloc: Mismatched usage flags: 246 x 410, usage 333
    05-22 17:38:04.283: W/GraphicBufferAllocator(49): alloc(246, 410, 1, 00000333, …) failed -22 (Invalid argument)
    05-22 17:38:04.293: E/(49): GraphicBufferAlloc::createGraphicBuffer(w=246, h=410) failed (Invalid argument), handle=0×0
    05-22 17:38:04.293: E/BufferQueue(370): [ScreenshotClient] dequeueBuffer: SurfaceComposer::createGraphicBuffer failed
    05-22 17:38:04.303: W/WindowManager(370): Screenshot failure taking screenshot for (246×410) to layer 21005
    05-22 17:38:04.313: D/AndroidRuntime(1049): Shutting down VM
    05-22 17:38:04.323: D/jdwp(1049): Got wake-up signal, bailing out of select
    05-22 17:38:04.323: D/dalvikvm(1049): Debugger has detached; object registry had 1 entries
    05-22 17:38:04.413: I/ActivityManager(370): Start proc com.test1 for activity com.test1/.Splash: pid=1060 uid=10059 gids={50059, 3003}
    05-22 17:38:04.493: D/dalvikvm(1060): Not late-enabling CheckJNI (already on)
    05-22 17:38:05.653: D/(1060): HostConnection::get() New Host Connection established 0xb7a05c58, tid 1060
    05-22 17:38:05.783: W/EGL_emulation(1060): eglSurfaceAttrib not implemented
    05-22 17:38:05.793: D/OpenGLRenderer(1060): Enabling debug mode 0
    05-22 17:38:05.973: I/ActivityManager(370): Displayed com.test1/.Splash: +1s621ms
    05-22 17:38:07.563: I/ActivityManager(370): START u0 {act=com.test1.MainActivity cmp=com.test1/.MainActivity} from pid 1060
    05-22 17:38:07.603: E/gralloc_goldfish(49): gralloc_alloc: Mismatched usage flags: 246 x 410, usage 333
    05-22 17:38:07.603: W/GraphicBufferAllocator(49): alloc(246, 410, 1, 00000333, …) failed -22 (Invalid argument)
    05-22 17:38:07.603: E/(49): GraphicBufferAlloc::createGraphicBuffer(w=246, h=410) failed (Invalid argument), handle=0×0
    05-22 17:38:07.603: E/BufferQueue(370): [ScreenshotClient] dequeueBuffer: SurfaceComposer::createGraphicBuffer failed
    05-22 17:38:07.603: W/WindowManager(370): Screenshot failure taking screenshot for (246×410) to layer 21010
    05-22 17:38:07.863: D/dalvikvm(1060): GC_FOR_ALLOC freed 47K, 5% free 3035K/3164K, paused 40ms, total 46ms
    05-22 17:38:07.863: I/dalvikvm-heap(1060): Grow heap (frag case) to 3.644MB for 635812-byte allocation
    05-22 17:38:07.913: D/dalvikvm(1060): GC_FOR_ALLOC freed 6K, 4% free 3649K/3788K, paused 45ms, total 45ms
    05-22 17:38:08.043: D/ITCRssReader(1060): main
    05-22 17:38:08.063: D/ITCRssReader(1060): AsyncTask #1
    05-22 17:38:08.243: W/EGL_emulation(1060): eglSurfaceAttrib not implemented
    05-22 17:38:08.483: I/ActivityManager(370): Displayed com.test/.MainActivity: +778ms
    05-22 17:38:13.123: W/dalvikvm(1060): threadid=12: thread exiting with uncaught exception (group=0xb3aa4b90)
    05-22 17:38:13.153: E/AndroidRuntime(1060): FATAL EXCEPTION: AsyncTask #1
    05-22 17:38:13.153: E/AndroidRuntime(1060): Process: com.worldcup, PID: 1060
    05-22 17:38:13.153: E/AndroidRuntime(1060): java.lang.RuntimeException: An error occured while executing doInBackground()
    05-22 17:38:13.153: E/AndroidRuntime(1060): at android.os.AsyncTask$3.done(AsyncTask.java:300)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.lang.Thread.run(Thread.java:841)
    05-22 17:38:13.153: E/AndroidRuntime(1060): Caused by: java.lang.NullPointerException: println needs a message
    05-22 17:38:13.153: E/AndroidRuntime(1060): at android.util.Log.println_native(Native Method)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at android.util.Log.e(Log.java:232)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at com.worldcup.MainActivity$GetRSSDataTask.doInBackground(MainActivity.java:62)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at com.worldcup.MainActivity$GetRSSDataTask.doInBackground(MainActivity.java:1)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at android.os.AsyncTask$2.call(AsyncTask.java:288)
    05-22 17:38:13.153: E/AndroidRuntime(1060): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    05-22 17:38:13.153: E/AndroidRuntime(1060): … 4 more
    05-22 17:38:13.173: W/ActivityManager(370): Force finishing activity com.worldcup/.MainActivity
    05-22 17:38:13.193: E/gralloc_goldfish(49): gralloc_alloc: Mismatched usage flags: 246 x 410, usage 333
    05-22 17:38:13.193: W/GraphicBufferAllocator(49): alloc(246, 410, 1, 00000333, …) failed -22 (Invalid argument)
    05-22 17:38:13.203: E/(49): GraphicBufferAlloc::createGraphicBuffer(w=246, h=410) failed (Invalid argument), handle=0×0
    05-22 17:38:13.203: E/BufferQueue(370): [ScreenshotClient] dequeueBuffer: SurfaceComposer::createGraphicBuffer failed
    05-22 17:38:13.203: W/WindowManager(370): Screenshot failure taking screenshot for (246×410) to layer 21010
    05-22 17:38:13.943: W/EGL_emulation(525): eglSurfaceAttrib not implemented
    05-22 17:38:14.623: D/LightsService(370): Excessive delay setting light: 60ms
    05-22 17:38:15.183: D/LightsService(370): Excessive delay setting light: 481ms
    05-22 17:38:21.193: I/Process(1060): Sending signal. PID: 1060 SIG: 9
    05-22 17:38:21.223: E/SoundPool(370): error loading /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.223: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.223: E/SoundPool(370): error loading /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.223: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.233: E/SoundPool(370): error loading /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.233: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.233: E/SoundPool(370): error loading /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.233: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.233: E/SoundPool(370): error loading /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.233: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    05-22 17:38:21.263: D/LightsService(370): Excessive delay setting light: 107ms
    05-22 17:38:21.283: E/SoundPool(370): error loading /system/media/audio/ui/KeypressStandard.ogg
    05-22 17:38:21.283: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
    05-22 17:38:21.283: E/SoundPool(370): error loading /system/media/audio/ui/KeypressSpacebar.ogg
    05-22 17:38:21.283: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
    05-22 17:38:21.283: E/SoundPool(370): error loading /system/media/audio/ui/KeypressDelete.ogg
    05-22 17:38:21.283: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
    05-22 17:38:21.283: E/SoundPool(370): error loading /system/media/audio/ui/KeypressReturn.ogg
    05-22 17:38:21.283: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
    05-22 17:38:21.283: E/SoundPool(370): error loading /system/media/audio/ui/KeypressInvalid.ogg
    05-22 17:38:21.283: W/AudioService(370): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
    05-22 17:38:21.283: W/AudioService(370): onLoadSoundEffects(), Error -1 while loading samples
    05-22 17:38:21.483: D/LightsService(370): Excessive delay setting light: 68ms
    05-22 17:38:21.513: I/ActivityManager(370): Process com.test1 (pid 1060) has died.
    05-22 17:38:21.633: D/LightsService(370): Excessive delay setting light: 65ms
    05-22 17:38:21.693: D/LightsService(370): Excessive delay setting light: 55ms

    Any help would be much appreciated.

    Thanks in advance,

    Geoff

    Reply
  29. abdellah says:

    Thanks for the tutorial that’s worked :) , but i have a little problem, the problem is, when i display my list i get the name of package plus a number ex:name_package@4b03f71c so i didn’t show the title, can you help me.

    Reply
  30. Osama says:

    Hi ITCuties, Everything was good until I Run the app the list view doesn’t catch the title but show the package name instead of the title showing like this

    com.osama.rssreaders.app.RssItems@b2e188f8 
    com.osama.rssreaders.app.RssItems@b2e182d8
    

    etc
    If i click on them it actually goes to the right page but the title is not coming through. I seem to me missing something.

    Reply
    • Andrew Rogers says:

      I had the same issue. By creating my own adapter corrected it. Hope this helps.

      //**************************************************
      public class childFragment1 extends Fragment{
      	
      	ArrayAdapter rssAdapter;
      	
      	
      	@Override
          public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
       
              
              // Creating view correspoding to the fragment
              View v = inflater.inflate(R.layout.childfragment1, container, false);
              
              
              
              GetRssDataTask task = new GetRssDataTask();
              
              task.execute(&quot;http://www.itcuties.com/feed/&quot;);
         
       
              return v;
          }
      	
      	
      	
      	private class GetRssDataTask extends AsyncTask&amp;lt;String, Void, List &amp;gt;{
      
      		@Override
      		protected List doInBackground(String... urls) {
      			
      			try{
      				RssReader rssReader = new RssReader(urls[0]);
      				
      				return rssReader.getItems();
      			}catch (Exception e){
      				Log.e(&quot;Test&quot;, e.getMessage());
      			}
      			return null;
      			
      		
      		}
      
      		//the below standard adapater does not work.
      		/*
      		@Override
      		protected void onPostExecute(List result) {
      			
      			ListView itcItems = (ListView)getActivity().findViewById(R.id.listView1);
              	
              	ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, result);
              	
              	Log.i(&quot;Test&quot;, &quot;Title = &quot; + result.get(0).getTitle());
              	
              	itcItems.setAdapter(adapter);
              	
              	itcItems.setOnItemClickListener(new ListListener(result, getActivity()));
      			
      			
      		}
      		
      		*/
      		
      		
      		@Override
      		protected void onPostExecute(List result) {
      			
      			ListView itcItems = (ListView)getActivity().findViewById(R.id.listView1);
      			
      			rssAdapter = new myListAdapter(getActivity(), result);
      			
              	itcItems.setAdapter(rssAdapter);
              	
              	itcItems.setOnItemClickListener(new ListListener(result, getActivity()));
      			
      			
      		}
      		
      		
      	}
      
      
      //**************************************************
      //Created another class called myListAdapter
      
      public class myListAdapter extends ArrayAdapter {
      
      	private final List list;
          private final Activity context;
          
        
          Context myContext;
         
          View cv;
          
          
          public myListAdapter(Activity context, List list) {
              super(context, R.layout.rssitemrow, list);
              this.context = context;
              this.list = list;
            
                
          }
          
          static class ViewHolder {
              //protected TextView text;
              protected TextView Text;
             
              
          }
          
          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
          	
      
              ViewHolder viewHolder = null;
             
              cv = convertView;
              
              if (convertView == null) {
              	
                  LayoutInflater inflator = context.getLayoutInflater();
                  convertView = inflator.inflate(R.layout.rssitemrow,null);
                  viewHolder = new ViewHolder();
                 
                  viewHolder.Text = (TextView) convertView.findViewById(R.id.tvRssItemTitle);
                  
                  
                  convertView.setTag(viewHolder);
                  convertView.setTag(R.id.tvRssItemTitle, viewHolder.Text);
                  
                 
                  } 
              	else 
              	{
                  viewHolder = (ViewHolder) convertView.getTag();
              }
              
              
              viewHolder.Text.setTag(position);
              viewHolder.Text.setText(list.get(position).getTitle());
              
             
              return convertView;
          }
      
      }
      
      //Created a layout for the rows
      
      Reply
  31. Kanwal says:

    Hi, Can you please tell me how can I fetch my featured image of my posts in the rss feed. Your previous tutorial was awesome.I am waiting for your response.

    Reply
  32. Raz says:

    Hi,
    i’m trying to get a rss feed from this url: http://www.telesport.co.il/sport_rss.ashx .
    but it’s just doesn’t work.
    the error I Get is

    java.lang.NullPointerException: Attempt to invoke interface method ‘int java.util.List.size()’ on a null object reference
    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
    at android.widget.ListView.setAdapter(ListView.java:487)
    at com.example.raz.win.MainActivity$GetRSSDataTask.onPostExecute(MainActivity.java:295)
    at com.example.raz.win.MainActivity$GetRSSDataTask.onPostExecute(MainActivity.java:268)

    Reply
  33. art says:

    hello
    thank s for toturial its worked but i have some link dos not return complete
    the link is likethet
    http://www…..com/index.php?module=cdk&func=loadmodule&system=cdk&sismodule=user/content_view.php&cnt_id=241113&ctp_id=93&id=793&sisOp=view
    but i get this:
    http://www…..com/index.php?module=cdk

    I think & in link cause problom

    do you have any idea to solve this problem

    Reply
  34. Kathan says:

    When i run the application only a white screen comes.
    Though i can quit the app,I am not able to see anything.
    Please help!

    Reply
  35. Reza says:

    Hello,

    i want to put more than one url to task.execute who can i do this?

    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>