• Mobile » Android »
  • Android Simple RSS Reader with Splash Screen and Custom List View.

Android Simple RSS Reader with Splash Screen and Custom List View.

RSS (Reach Site Summary):

RSS is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format. – wikipedia

Basically RSS are xml files. We can read RSS files using applications called RSS Readers. In this tutorial we will create a ‘Simple RSS Reader’ app with some basic functionalities like:

1. A splash screen with a spinner and background image shown while the data XML being parsed.

2. From the feed returned by the Parser displaying the thumbnail image, title & date in a custom List View.

2. On click of the list item, the description shown in a separate Activity.

Here’s the final demo of the ‘Simple RSS Reader’ App on a emulator:

Analyzing the XML:

In this tutorial is used an external ‘xml’ (RSS) of the website [http://www.androidcentral.com]

RSS Link: http://www.mobilenations.com/rss/mb.xml

You can see the structure of the XML(tags) used in it by going to the code view of the link. Here is the example ‘item’ <tag> used in the XML:

<item>

<title>Voice Controlled: A guide to using speech with Windows Phone 8</title>

<description>
<div id="comment-wrapper-nid-13725" ></div>
<div><div><div>
<p style="" >
<img
alt="Getting chatty with Windows Phone 8"
height="365"
src="http://cdn.wpcentral.com/sites/wpcentral.com/files/styles/large/public/field/image/2012/11/HandHolding_Speech_ws.jpg"
width="650" />
</p>
<p
Speech has always been a part of Windows Phone and it has offered some nice ways of interacting with your handset by using your voice alone.
</p>
<p>
We have put together a guide that should suit those that are new to Windows Phone and also to those that have upgraded to
<a href="http://www.wpcentral.com/windows-phone-8" >
Windows Phone 8 </a>. Interacting with voice recognition and commands can be a powerful and time saving way to use your phone efficiently and even safely.
</p>
<p>
</p>
</div></div></div>
<div><div>Tag: </div><div><div>
<a href="/tag/windowsphone8" >
windowsphone8
</a>
</div>
<div>
<a href="/tags/speech" >speech</a>
</div>
<div>
<a href="/tags/how" >how-to</a>
</div>
<div>
<a href="/tags/text-speech" >Text to Speech</a>
</div>
<div>
<a href="/tags/text-voice" >text to voice</a>
</div>
<div>
<a href="/tags/wp8" >WP8</a>
</div>
<div>
<a href="/tags/wp7" >wp7</a>
</div>
</div>
</div>
<div><div><div>
<a href="/category/how" >How To</a>
</div></div></div>
</description>

<link>http://www.wpcentral.com/voice-controlled-guide-using-speech-windows-phone-8</link>

<pubDate>Thu, 22 Nov 2012 14:12:52 +0000</pubDate>

<guid isPermaLink="<a>false</a>">13725 at http://www.wpcentral.com</guid>
<dc:creator>robert brand</dc:creator>

</item>

Here from the above <item> we need to get some of the elements for our app, like we need a title(<title></title>) description(<description></description>) publication date(<pubDate></pubDate>) and finally a thumbnail image.

But as you can see in the item we dint find a image tag or any tag related to the image, but if you observe the description we have a image link inside it with in HTML tags. So to get he image link we need to parse the HTML description for ‘<img src=” image link”>’ .

So here we have to perform html parsing over the description which we will get after parsing the XML. So we need an HTML Parser, we use an external library called ‘jsoup’ to perform this html parsing. The library can be downloaded at: http://jsoup.org/download. Add the library to the project.

Also i used some external classes from: https://github.com/thest1/LazyList to Lazily load the images in the ListView. Here are the list of classes i used :

  • FileCache.java
  • ImageLoader.java
  • MemoryCache.java
  • Utils.java

Now lets get started with building process step by step:

step 1: Create a New Project (‘Simple RSS Reader’) with some package name & a default blank Activity.

Creating a Splash Screen:

step 2 : As you seen in the video demo a splash screen is shown on launch of the app where all the parsing of the data from the XML is done. So first lets create a Splash Screen Activity: SplashActivity.java(You can rename the blank activity created).

Next we need to create a layout for the Activity. Use a Relative layout to show an image and a loading spinner with some text below it. The final Layout file will look like this:

splash.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/app_name"
android:src="@drawable/mwm_small" />

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:orientation="horizontal" >

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:text="@string/loading" />
</LinearLayout>

</RelativeLayout>

In the SplashActivity.java set the content view to the layout created: setContentView(R.layout.splash);

step 3: Now before starting the parsing process we need to check for the Internet connectivity. If we are connected then we can proceed with the parsing else we will show an alert to check for connectivity. The following code shows how to check for connectivity and displaying a Dialog if there’s no connectivity:

ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});

AlertDialog alert = builder.create();
alert.show();

} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}

Here’s the result of the above layout:

Parsing the XML:

step 4: We need to perform the parsing in a separate thread, we achieve that by using the ‘AsyncTask’ Class. The reason to perform the parsing in a separate thread is if you start the parsing in the main thread or the UI thread then the application may clog as the Parsing is a potentially a time taking process.

So we create a sub class called ‘AsyncLoadXMLFeed’ which extends AsyncTack. In the class we implement the methods: doInBackground() and onPostExecute(). In doInBackground() method we start the Parsing process and once if the Parsing has done then it triggers the onPostExecute() method where we can perform action that has to be done after Parsing(starting the List Activity).

DOM Parser:

step 5: Before jumping in to the parsing we create two classes called: ‘RSSItem’ and ‘RSSFeed’ both implements Serializable.

RSSItem: This class contains the String variables which holds the required data from each item in the XML. We have also some setters and getters to set and get the item data. Here the final RSSItem class:

RSSItem.java‘:

public class RSSItem implements Serializable {

private static final long serialVersionUID = 1L;
private String _title = null;
private String _description = null;
private String _date = null;
private String _image = null;

void setTitle(String title) {
_title = title;
}

void setDescription(String description) {
_description = description;
}

void setDate(String pubdate) {
_date = pubdate;
}

void setImage(String image) {
_image = image;
}

public String getTitle() {
return _title;
}

public String getDescription() {
return _description;
}

public String getDate() {
return _date;
}

public String getImage() {
return _image;
}

}

RSSFeed: This class object holds all the Items (RSSItem’s) that have been parsed. It contains a List where we add the RSSItems by a method called addItem(RSSItem item):

List<RSSItem> _itemlist;

void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}

We have also a method called getItemCount() to get the total number of items in the feed.

The final RSSFeed class is here:

RSSFeed.java

public class RSSFeed implements Serializable {

private static final long serialVersionUID = 1L;
private int _itemcount = 0;
private List _itemlist;

RSSFeed() {
_itemlist = new Vector(0);
}

void addItem(RSSItem item) {
_itemlist.add(item);
_itemcount++;
}

public RSSItem getItem(int location) {
return _itemlist.get(location);
}

public int getItemCount() {
return _itemcount;
}

}

step 6: Now we need to create a Parser class where it takes the url and performs the Parsing. We write some conditions to check for the tags and we set the RSSItems and finally the RSSFeed.

In this example we use DOM Parser to Parse the XML data. We create a class called ‘DOMParser’ in which we create a method of type RSSFeed called parseXML(String xml) which takes in a url as parameter. Once the Parsing is done the method returns the feed(RSSFeed) object:

private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// Parser the XML and Return the RSSFeed Object(_feed).
return _feed;
}

Here is the final ‘DOMParser.java‘ :

public class DOM_Parser {

private RSSFeed _feed = new RSSFeed();

public RSSFeed parseXml(String xml) {

URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

try {
// Create required instances
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();

// Get all  tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();

for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();

NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();

// Get the required elements from each Item
for (int j = 1; j < clength; j = j + 2) {

Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();

theString = nchild.item(j).getFirstChild().getNodeValue();

if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}

else if ("description".equals(nodeName)) {
_item.setDescription(theString);

// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}

else if ("pubDate".equals(nodeName)) {

// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}

}
}

// add item to the list
_feed.addItem(_item);
}

} catch (Exception e) {
}

// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}

}

step 7: Now we have our Parser ready. In the Splash Activity we now call the method parseXml(String xml) from the DOMParser class with the URL we got(http://www.mobilenations.com/rss/mb.xml) as the parameter:

DOMParser myParser = new DOMParser();
feed = myParser.parseXml("http://www.mobilenations.com/rss/mb.xml");

Once after the feed has been obtained in the onPostExecute() method we need to start the ListActivity and pass it the feed we got, we do that by bundling the feed object and attaching it to the Intent:

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);

// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);

step 8: The final ‘SplashActivity.java‘ will looks as follows:

public class SplashActivity extends Activity {

private String RSSFEEDURL = "http://www.mobilenations.com/rss/mb.xml";
RSSFeed feed;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.splash);

ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null
&& !conMgr.getActiveNetworkInfo().isConnected()
&& !conMgr.getActiveNetworkInfo().isAvailable()) {
// No connectivity - Show alert
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});

AlertDialog alert = builder.create();
alert.show();

} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();

}

}

private class AsyncLoadXMLFeed extends AsyncTask {

@Override
protected Void doInBackground(Void... params) {

// Obtain feed
DOM_Parser myParser = new DOM_Parser();
feed = myParser.parseXml(RSSFEEDURL);
return null;

}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);

// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);

// kill this activity
finish();
}
}
}

Custom List Activity:

step 9: To display the feed items in a list we need to create a custom List View with each List item containing a title, a thumbnail image & a date. Creating a custom list view has been posted in the previous tutorial titled: Android simple & custom List views with examples.

Please refer the above mentioned post to understand how to create a custom list view.

A screen shot of the Custom List that we are going to achieve is shown below:

Here are the files i used to create the above Custom List View:

Layout files:

feed_list.xml‘:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>

</LinearLayout>

list_item.xml‘:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="2dp" >

<ImageView
android:id="@+id/thumb"
android:layout_width="60dp"
android:layout_height="60dp"
android:contentDescription="@string/app_name" />

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/arrow"
android:layout_toRightOf="@+id/thumb"
android:orientation="vertical" >

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="@string/title"
android:textSize="16dp"
android:textStyle="bold" />

<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="@string/date"
android:textColor="#7F7F7F"
android:textSize="10dp" />
</RelativeLayout>

<ImageView
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:contentDescription="@string/app_name"
android:src="@drawable/arrow_next" />

</RelativeLayout>

ListActivity.java‘:

public class ListActivity extends Activity {

Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.feed_list);

myApp = getApplication();

// Get feed form the file
feed = (RSSFeed) getIntent().getExtras().get("feed");

// Initialize the variables:
lv = (ListView) findViewById(R.id.listView);
lv.setVerticalFadingEdgeEnabled(true);

// Set an Adapter to the ListView
adapter = new CustomListAdapter(this);
lv.setAdapter(adapter);

// Set on item click listener to the ListView
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
// actions to be performed when a list item clicked
int pos = arg2;

Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
Intent intent = new Intent(ListActivity.this,
DetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("pos", pos);
startActivity(intent);

}
});

}

@Override
protected void onDestroy() {
super.onDestroy();
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}

class CustomListAdapter extends BaseAdapter {

private LayoutInflater layoutInflater;
public ImageLoader imageLoader;

public CustomListAdapter(ListActivity activity) {

layoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}

@Override
public int getCount() {

// Set the total list item count
return feed.getItemCount();
}

@Override
public Object getItem(int position) {
return position;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// Inflate the item layout and set the views
View listItem = convertView;
int pos = position;
if (listItem == null) {
listItem = layoutInflater.inflate(R.layout.list_item, null);
}

// Initialize the views in the layout
ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);
TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
TextView tvDate = (TextView) listItem.findViewById(R.id.date);

// Set the views in the layout
imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
tvTitle.setText(feed.getItem(pos).getTitle());
tvDate.setText(feed.getItem(pos).getDate());

return listItem;
}
}
}

In the above List Activity in the Adapter class to set the thumbnail image we used the ‘ImageLoader’ Class which we copied to Project earlier along with some other supporting classes.

And in the onItemClickListner(), we are Passing the feed along with the position of the item clicked to the ‘DetailActivity’.

step 10: So lets now create the ‘DetailActivity’ which takes in the feed and position to display the title and the full description in a WebView.

The Layout used in detail Activity should contain a TextView to hold the title and a WebView to hold the description. (As the description we got from the parser is a HTML text we need the WebView to display the description instead of a TextView.)

The final ‘detail.xml‘ will looks like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="2dp" >

<ImageView
android:id="@+id/thumb"
android:layout_width="60dp"
android:layout_height="60dp"
android:contentDescription="@string/app_name" />

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/arrow"
android:layout_toRightOf="@+id/thumb"
android:orientation="vertical" >

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="@string/title"
android:textSize="16dp"
android:textStyle="bold" />

<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="@string/date"
android:textColor="#7F7F7F"
android:textSize="10dp" />
</RelativeLayout>

<ImageView
android:id="@+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:contentDescription="@string/app_name"
android:src="@drawable/arrow_next" />

</RelativeLayout>

Here’s the result of the above layout:

In the ‘DetailActivity’ we created, we need to get the feed and the position that has been passed from the List Activiy. We can get the Intent data by using getIntent() method:


RSSFeed feed = (RSSFeed) getIntent().getExtras().get("feed");
int pos = getIntent().getExtras().getInt("pos");

And once we got the feed and the Position we can set the views in the Layout. The final ‘DetailActivity’ will looks like this:


public class DetailActivity extends Activity {

RSSFeed feed;
TextView title;
WebView desc;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);

// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);

// Get the feed object and the position from the Intent
feed = (RSSFeed) getIntent().getExtras().get("feed");
int pos = getIntent().getExtras().getInt("pos");

// Initialize the views
title = (TextView) findViewById(R.id.title);
desc = (WebView) findViewById(R.id.desc);

// set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.getPluginState();
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);
ws.setBuiltInZoomControls(true);

// Set the views
title.setText(feed.getItem(pos).getTitle());
desc.loadDataWithBaseURL("http://www.androidcentral.com/", feed
.getItem(pos).getDescription(), "text/html", "UTF-8", null);
}

}

step 11: Do not forget to register the Activities in the Manifest and also set the required permissions:

The final Manifest will look like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.td.rssreader"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />

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

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".SplashActivity"
android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ListActivity" />
<activity android:name=".DetailActivity" />
</application>

</manifest>

We are done now! Run the Application!

Download Sources:

TD Simple RSS Reader

In up coming tutorials we talk about bringing this ‘Simple RSS Reader’ to a beautiful RSS Reader Application by adding the features like: Offline Reading, pull to refresh List, Swipe through the Details,  Action Bar,  Font size increase and decrease in the description view and more other miscellaneous features.

* Playing Youtube videos:

One way is to install flash on the device or the emulator on which you are installing the App.

The other way is to use the external library which takes care of playing the video. I would suggest this library http://code.google.com/p/android-youtube-player/downloads/list

Download the jar add it your Project.

In the description class where you want to play the video add a button image overlay over the webview or the ImageView and onClick of the button start the Video Intent:


String url = feed.getItem(position).getLink();
String Vid = null;
Pattern pattern = Pattern.compile("embed/(.*?)\\?");
Matcher matcher = pattern.matcher(url);
if (matcher.find())
Vid = matcher.group(1);
if (Vid != null) {
Intent videoIntent = new Intent(null, Uri.parse("ytv://" + Vid),
GM_Video_Desc.this, OpenYouTubePlayerActivity.class);
startActivity(videoIntent);
}

Also do not forget to register the activity and to add the required permissions  in Manifest:

uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_WIFI_STATE"

<activity
android:name="com.keyes.youtube.OpenYouTubePlayerActivity"
android:screenOrientation="landscape" />

email
Hi this is Chanu! Admin of TD. I am a Tech enthusiast and have passion towards mobile Dev. I love Blogging and WEB. I currently work on Technologies like: Java, Android, iOS, PHP, DotNet, CMS. I like to play with new and hot Technologies. I mostly believe in " Solve a real life Problem and the World will be yours "

This entry was posted in Android

80 Responses

  • Hello,

    Few questions, firstly I’m new to android development so hope you don’t mind.
    Anyway, How would I parse videos and allow users to watch videos that come in the RSS stream.
    Secondly, How would I only allow images with certain HTML class id’s (In the description tag, inside the RSS xml file), say If I want the webview to hide an image with class tag as ‘hidden’.

    Thank you in advanced.

    Reply
    • Hi lonehangman,

      You would probably looking for a HTML Parser. In this tutorial i used ‘Jsoup’ parser to parser he HTML data. It’s a fully customized, so that you can get a specific Tag data and more specifically the attribute data also, all that you need is to pass the ‘tag’ and ‘attribute’ names. For more details please refer: http://jsoup.org/

      And if you want to hide a specific tag then just find the tag(string) you don’t want to display in the WebView and then replace it with null(“”) from the whole html(string) using String replace function.

      Reply
      • Thanks. I’ve hidden the images I don’t want. But now the only thing that I am having problems with is playing youtube videos. I can play vimeo videos fine but not youtube. Is it something to do with HTML5/Flash or something else.

        I’m parsing it correctly (I think).

        Reply
        • Hi, updated the post with how to play youtube videos. Hope that helps.
          FYI: http://stackoverflow.com/questions/2292086/play-youtube-video-in-webview

          Reply
          • Thanks!

            Reply
          • Also, when you get around to the pull to refresh part, it get’s a bit frustrating.

            I’ve gone through a few libraries and they all don’t work with this project. You can set it up fine and get all the backend working as well as the UI of it, but in the actual list view if you touch an item it will go to the next item in the list view, and if you touch the last item in the list it just crashes.

            So, with that…Have fun :/

            Reply
            • You’re welcome. I hope the problem is with your code not with the compatibility of libraries (try passing one less position (pos = pos-1) to the description view). Anyways am going to achieve the refresh by using the Action Bar item for the next RSS Reader tutorial. May be i will post one on Pull to refresh in another tutorial.

              Reply
  • Hi. Very Compliments for the post, but I have a problem. I have a menu that launch more activity, but when I launch the “feed activity”, the splashscreen appears but after a few seconds the app crash. I don’t understand where is the error. Can you help me please?
    Thanks in advance.
    Giancarlo

    Reply
  • Thanks for your help. I have solved the problem.

    Reply
  • Excellent Job! but some RSS URLs wouldn’t work.. specially like .net websites.. http://www.dotnetnuke.com/Resources/Blogs/rssid/21.aspx

    Reply
  • Thanks! It says it’s caused by utf-8 bom encoding on the xml file. I also found a similar issue here. http://stackoverflow.com/questions/13648921/how-to-parse-rss-feed-from-net-website

    Reply
  • My hat is off to you. This is by far the best RSS Image tutorial on the internet! I have followed all of them, I have literally went to the end of the internet looking for a correct up-to-date RSS Image Feed for Android and please look no further because here it is! This is a great piece of code and I look forward learning more from you.

    Thank you,
    Kyle

    Reply
    • Great thanks! you gave me the boost what all bloggers would love. Here on ‘techiedreams’ am sharing my experiences and first of all am a learner, so hope for the best tutorials.
      by the way wait for the Part 3 of RSS reader series, it will be more interesting: Introducing ActionBar with animated items, Refreshing and more…

      Reply
      • Since I can’t reply to your other comment, here will do fine.
        Thanks for the pos – 1 tip. I was thinking of that exact method, but didn’t know where to change it.
        But I got the pull to refresh UI to work perfectly (I’m going to work on the refreshing part as soon as I’m done with the video stuff).

        If you do decide to do a tutorial about it (Pull to refresh) use the chris banes library on github. It takes a little bit of tinkering to get it properly working, but it works.
        Just put change line 100 (Might be different for you, but it’s the [intent.putExtra("pos", pos);] line), to intent.putExtra(“pos”, pos-1);
        But do it after you put the pull to refresh part in, otherwise it will cause a few problems.

        Thanks again.

        Reply
        • Very thanks for the comment. Please wait am going to post the RSS third part tomorrow with the refresh using the animated Action bar item, also added some features..
          And i would recommend you to mostly use the default options rather than going for the third party libraries. Include an action bar to your project too (use ‘ActionBarSherlock’ to support for all devices 2.0+).

          Reply
  • hi

    link to open ? code share ?

    Reply
  • I downloaded it but my problem is different. I want to show link bat you are show description me

    Reply
    • Sorry i couldn’t understand your problem yet! please elaborate on the issue, so that i can provide a good solution.

      Any ways if you want to get the description text use feed.getItem(pos).getDescription();

      Reply
  • http://g1212.hizliresim.com/14/9/gr8g1.png

    I want to take the contents of a link

    Domparser.java

    else if (“link”.equals(nodeName)) {
    _item.setDescription(theString);

    String html = theString;
    org.jsoup.nodes.Document docHtml = Jsoup
    .parse(html);

    Elements body = docHtml.select(“body”);
    _item.setLink(body.html());

    }
    I’ve done things like this, but.. Not work.

    Reply
    • I got you problem, First check for the tags you want to pick from the html and then use the appropriate functions from this link: http://jsoup.org/cookbook/extracting-data/dom-navigation.

      Element content = doc.getElementById(“content”);
      Elements links = content.getElementsByTag(“a”);

      May be one of these would help.

      Reply
    • What helped me pull the images out was just commenting out the jsoup and just pulling the whole link bc my RSS did not have the image hidden in the one of the nodes. So the DOMparser just pulled the whole link and the imageloader took care of the rest.

      Reply
  • Ok, this will be my last ever question, because I now have a good understanding of Java and android development.

    When implementing the youtube player library, how would it work for lots of videos.

    Reply
  • Chanu, I couldn’t find your email address to PM you, but I wanted to bother you also…I am trying to combine your RSS example and your Gridview example. I would like to have a Grid of RSS images and then have a person click on the image and go to the link. I am lost…any guidance would be great.

    Thanks,
    Kyle

    Reply
    • Hi Kyle, you could use the grid view instead of the custom list and its a simple change. On click of the grid item now you pass the item position and feed to the new activity where you show the total description.

      Here’s my email id: getchanu@gmail.com

      Reply
      • Once again you are correct –
        I just commented out the listview lv in the ListActivity;
        then replaced all the listview’s with Gridview gv;
        and replaced the corresponding RSS apk xml files with the Gridview xml’s;

        I have the Image RSS gridview (which is awesome), now I am figuring out the link to the website activity.

        Do you know how to get rid of the horizontal spacing, it is annoying haha. I set my padding to (0,0,0,0) and I put android:adjustViewBounds”true” and still the spacing?

        Thank you once again. I am also a learner, so this is great stuff.

        Kyle

        Reply
        • android:columnWidth="80dp"
          android:horizontalSpacing="10dp"
          android:numColumns="auto_fit"
          android:stretchMode="columnWidth"
          android:verticalSpacing="10dp"

          Try playing with these properties of the grid view.

          Reply
  • Hi chanu!I have an ather question for you (i hope you can help me): how can I activate full feed of my wordpress blog using feedburner? In the app that i have created following your post, I notice that my feeds are parzial and not complete like yours. Wich service have you used to activate full feeds of your site?
    Thanks in advance
    Giancarlo

    Reply
  • Also under settings in the Reading section set the option: ‘For each article in a feed, show’ to Full text

    Reply
  • hi chanu!i have downloaded jatpack plugin and i have setted the full feed text option in wordpress settings but nothing is changed..wich settings in jetpack enable the full text?i have a blog in wordpress.org and not in wordpress.com… Could you please send me by mail the instructions to set correctly jetpack?
    Thanks in advance.
    Giancarlo

    Reply
    • In the DOMParser.java file, look for the part where it says else if <"description" …
      change the "description" part to "content:encoded". This is something that wordpress does to keep safe(?)

      Reply
  • Tutorial is nice.But Please provide simple rss reader source code which you demonstrate. I am getting runtime error that,”An error occured while excecuting doInBackground()”

    Reply
  • Hi..I found the error and rectified..No thanks..really superb tutorial..And recently I downloaded an apps in which i was admired with the tabs https://play.google.com/store/apps/details?id=com.eurosport&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5ldXJvc3BvcnQiXQ..and I found tat it has been done through android sherlock.So how to implement this rss reader through sherlock fragments ie through tabs.? If you have an idea pls share it..Thanks in advance..:)

    Reply
  • @varnmar. s it has been done through sherlock,Tabpage indicator and pull to refresh been used…Hi.@chanu..Nice tutorial.keep rocking…Will you please explain how to add this rss in Tabpage indicator? Currently most of the apps are switched to sherlock,so tabs are quite different.Awaiting for your post.

    Reply
  • Hi.@chanu..Nice tutorial.keep rocking…Will you please explain how to add this rss in Tabpage indicator? Currently most of the apps are switched to sherlock,so tabs are quite different.Awaiting for your post.

    Reply
  • Hi.tutorial was superb..I have a doubt tat,Is it possible to directly load in listview,instead of using splash screen activity? If so,how?

    Reply
  • Hi,This is very nice tutorial,,,,i have one issue with connection verification,the SplashActivitie don’t watch alert in case that internet connection is not available,,,how can i fix it? another question is How can i pass the feed to MainActivity that instantiate SherlockFragments that should contain listView with data from this feed,,,fr example suppose that feed contains sport news,economic news,science news,,,,and so on ,and we have SportFragment,EconomicFragment,,,,so the SportFragment should contains just feeds item which related just for Sport,,,,,Thank you in advance

    Reply
  • Good tutorial,,,,,but when you parsed the feed from XML why you did ”
    for (int j = 1; j < clength; j = j + 2) " instead of "
    for (int j = 1; j < clength; j = j + 1) " ?

    Reply
  • Hi,
    I have an xml url “http//www.example.com/file.xml”
    contains this informations:

    elm1
    desc1
    cat1

    elm2
    desc2
    cat1

    elm3
    desc3
    cat1

    elm4
    desc4
    cat1

    elm1
    desc1
    cat2

    elm2
    desc2
    cat2

    elm3
    desc3
    cat2

    elm4
    desc4
    cat2

    in java code i have a string”String title[]=new String[]{null};”

    i have a feed “feed” wich parse this xml file.

    i did a loop :

    for (int i=0;i<feed.getItemCount();i++)
    {
    if("cat2".equals(feed.getItem(i).getCategory())
    {
    title[i]=feed.getItem(i).getTitle();
    }
    }

    but title String contains nothing and my application don't work.
    but if i do Toast.maketText(getActivity(),feed.getItem(6).getCategory(),toast.LENGTH_LONG).show();
    I get "cat2" contains whitespace

    Reply
  • Hi chanu!
    I have a question: it’s possible to show a link to the article of the blog at the end of DetailActvity? I have the problem with the partial feed of my blog that I can’t solve and so I decided to proceed in this way. If it is possible, how can i modify the source code? Sorry, but i am a beginner in android programming.
    Thanks in advance.
    Giancarlo

    Reply
  • Hi Chanu!
    I have a question: it’s possibile to show a link to the post of the blog at the end of DetailActivity? I have the problem with the partial feed of my blog that i can’t solve and so I decided to proceed in this way. If it is possible, how can i modify the source code? Sorry, but i am a beginner in android programming.
    Thanks in advance.
    Giancarlo

    Reply
    • What site are you trying to get a feed from? I had this problem too, but I fixed it.

      Reply
    • Are you trying to display the link or setup a subsequent WebView?

      Reply
      • Hi!
        I have changed my target. Now I would like to insert a button in the dettailativity.java that showing the article in the blog after press it. I have inserted the button but I don’t know how modify the code to show the article into my blog.
        If you have a solution, I would be grateful.
        Thanks in advance!
        Giancarlo.

        ps: sorry for my english!

        Reply
        • Do you mean a WebView of the article (loads the web page)?
          To do that you need to pass the feed to the button’s OnItemClick and start a WebView Activity. And load the article’s url in the new webView Activity.

          No worries about the engllish, but I would advise you to learn the terms i.e. WebView etc etc when you ask for help that way it doesn’t matter how bad your english is :)
          Kyle

          Reply
  • Great App, it seems to work with your website but when I try a website like reading my school’s feed. It stops working the website for my schools feed is… http://feeds.feedburner.com/lasierranews?format=xml

    Thanks in advance

    Reply
    • Carlos,
      I have used Chanu’s program multiple times and it works the best on individual feeds. Plus also check out the encoding, “ISO-8859-1″ not the standard UTF-8. I have never used it on a feedburner site before.

      Reply
  • So what do you recommend?

    Reply
  • Mr . Chanu , Thank you for your Great effort
    but i have problem can’t show any rss feeds and have MemoryCache will use up to 6 MB
    in logcat
    can you help me ?

    Reply
  • How to add tab layout to the listview activity of this project? please help.

    Reply
  • hi, do you know how to retreive absolute path of an image in description tag? For example: . Thank for the great tutorial :)

    Reply
  • Hi Chanu.
    I couldn’t manage to play youtube videos in this code you shared. I have images and youtube videos in my rss feed. There is nothing wrong with the images, but embedded youtube videos are not working. I just get a black screen along the video frame.
    I imported the jar file, added the image button and added your code after websettings in DetailActivity class. Would you explain this process in detail please. Thank you so much.

    Reply
    • If you read in previous comments, you can see I had this issue previously. And now since I’m quite proficient in android development I can help you! :D

      What I did was used jsoup to get all the iframe tags, and then used regex to get the youtube video ID from the ID tags. With this ID, I put it in a youtube url that will return the video thumbnails. I then got rid of the iframe tags and replaced them with their thumbnails (Which if you touch, will open the youtube app and show the video)

      Here is the code that I used:

      http://pastebin.com/ejWK8LDW

      Sorry if it’s confusing

      Reply
      • Thank you for your sharing but i have “body cannot be resolved” problem in line: “for (Element e : body.select(“iframe”)) ” I dont have a definition of body in my Class. By the way i used these code in DetailActivity.java .I understand your solution but i couldn’t apply it :) Thank you again.

        Reply
  • Hi,can u help me?Could you show the source code of your application? I can not parse feeds different from that shown in this tutorial(

    Reply
  • Whomever you are, i would like to say thank you so much for this tutorial. I have been working on how to build RSS readers to learn more about xml parsing and uploading and displaying web content from the net into an app, and this is the first RSS demo app that I have come across that actually works 100%. Awesome job sir.

    Reply
  • mitchell vaughan April 23, 2013 at 3:20 pm

    Copied all classes and code in exactly as shown but it won’t move past the Splash activity. Any thoughts?

    Reply
  • I downloaded and ran your application. I want to do exactly the same application. But, Error and shuts down.

    jsoup-1.7.1.jar ===> Library add ==> but Reference library. Could this be the reason for the closure of the application?

    Sending a picture of the error.

    http://i43.tinypic.com/11kilmr.png

    How do I fix this error?

    Reply
    • You need to add jsoup to your libs folder and then include it in the build path, make sure it is imported into your DOMParser Class. In most cases when there is a DoInBackground Async error it is due to your parser class bc it is unable to DoInBackground (parsing).

      Reply
      • Problem solved thanks. I do not want to be a splash screen. How to make changes. Could not figure out Instead, I want the text loading.

        Reply
  • Hey, I’m not getting little thumbnail icons like you are with List_item.xml/ListActivity.java, is there a specific code that needs to be extracted from the RSS feed that I do now know about? Currently I’m writing my own example RSS so I’d love to know what I need to do to get the thumbnails showing up!

    Thovex

    Reply