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 Rss Reader Example 1: How to Use ListView and ArrayAdapter
- Android Rss Reader Example 2: Load Data by HTTP Request in Android
- Android Rss Reader Example 3: Parse XML in Android
- Android Rss Reader Example 4: Drag to Refresh ListView
- Android Rss Reader Example 5: Show WebSite Content in WebView
- Advanced Tutorial 6: Load Featured Image In ListView From Rss Feed
- Advanced Tutorial 7: Add Android Navigation Drawer Menu
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
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
The subclass of AsyncTask is HTTPDownloadTask. Do you know inner class in Java?
Hey James,
I didn’t understand how exactly to call that subclass from the MainActivity !
Thank you
new HTTPDownloadTask().execute(urlString);
Thank you
I am getting error at POSTDATA[]. Kindly tell me the solution.
The solution is define a POSTDATA[] variable in your main class. Please the rss reader source code here, if you still have problem on it.
Hi James, anytime i try to add the HTTPDownloadTask class to the main activity i get error. Can you please help me with it?
The first line should be: PostData[]
What is supposed to go to the comment side in the AsyncTask?
And also where am I supposed to put my RSS feed link?
Store in class variable and pass to RssDataController to load
Comment side is nothing, you can ignore in your code.
Hi Jim,
Thanks for the helpful guide.
How should i replace the data generated in generateDemoDate method with the information from rss?
First, you need to follow this android rss tutorial 3 to parse the xml, then fill in the parse result into the array.
Thanks