In Rss Reader Android App Tutorial 1, I gave an example to show how to use ListView and ArrayAdapter to build a simple Rss Reader UI layout. Inside the example, I am using dummy data which is predefined in the app. In this android app tutorial, I will use HttpURLConnection to download the data from a real website in background thread.

This is the 2nd Android tutorial about how to create a Rss Reader Android App. Before staring to read this Android tutorial, you may want to read the following android tutorial as well.

Android Download Data in Background Thread

If we implement loading data by HttpURLConnection in a wrong approach, it may causing android user interface to freese. That is because the network operations may take time to finish the request. During the time, the UI will hang till the loading process finishes. To avoid UI freezing problem, we have to load data on a different thread from the UI thread. We can use thread to load data on Android or use Asynctask.

What’s the difference from Asynctask and Thread in Android

There are many android developers asking me the same questions. What’s the difference from thread and asynctask in android? Which implementation should I choose, thread or asynctask? Even several days ago, one developer asked me if he can use thread in his apps to load image asynchronous. The reason he asked this question because he found an Android development guide says using Asynctask to loading data in background.

Both of Thread and AsyncTask can handle loading data in background and prevent UI from freezing. Unfortunately, using thread may make your code more complicated and more difficult to read. To free this problem, I suggest to use AsyncTask instead. It simplifies the creation of time consuming tasks which need to communicate with the user interface. AsyncTask takes care of the thread management. For more information about AsyncTask, you can refer this android example code: Download Images by AsyncTask in ListView

Download Data from Internet by HttpURLConnection

As Android document mentioned, AsyncTask can only used by subclass. Hence, I will create a subclass of AsyncTask in MainActivity class, and implement the HTTP request in the subclass. Here is the example code of subclass of AsyncTask:

	private class HTTPDownloadTask extends AsyncTask< //comment >
String, 
Integer, 
PostData[]> {

		@Override
		protected PostData[] doInBackground(String... params) {
			// TODO Auto-generated method stub
			String urlStr = params[0];
			InputStream is = null;
			try {
				URL url = new URL(urlStr);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setReadTimeout(10*1000);
				connection.setConnectTimeout(10*1000);
				connection.setRequestMethod("GET");
				connection.setDoInput(true);
				connection.connect();
				int response = connection.getResponseCode();
				Log.d("debug", "The response is: " + response);
				is = connection.getInputStream();
				
				//read string
				final int bufferSize = 1024;
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				while(true) {
					int count = is.read(buffer, 0, bufferSize);
					if(count == -1) {
						break;
					}
					
					os.write(buffer);
				}
				os.close();
				
				String result = new String(os.toByteArray(), "UTF-8");
				Log.d("debug", result);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
		}
		
	}

Next: Parse XML Data in Android

In the example code, I am using HttpURLConnection to download the data from url. Then, I use ByteArrayOutputStream to read all data from InputStream. For debug purpose, I print out the data to Log console. After we get the rss feed data from Website, we will parse the RSS Feed xml for render the ViewList.

Go to next tutorial: Parse XML in Android

Previous PostNext Post

15 Comments

  1. Hey James,

    You mentioned “Hence, I will create a subclass of AsyncTask in MainActivity class, and implement the HTTP request in the subclass.” in the above tutorial. How do we go about this? I tried adding a subclass in my MainActivity Java called AsyncTask but still getting error. Also getting an error in the subclass when I paste the above code.

    Kindly get me through this process.

    K

  2. Hi James, anytime i try to add the HTTPDownloadTask class to the main activity i get error. Can you please help me with it?

  3. Hi Jim,
    Thanks for the helpful guide.
    How should i replace the data generated in generateDemoDate method with the information from rss?

Leave a Reply

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