Hi friends ,
In this tutorial ,i'm going to describe
about how to fetch data from rss feed.Here i had also problem ,when i
was developing my recent project.I had also faced many problem
and at last i developed my best project.Here is the code that describe how to fetch news headline from rss
This class describes how to parse XML data:
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import android.util.Log;
import android.util.Xml;
public class XmlFeedParser {
//Feed Parsing Method
public ArrayList<Implement> parse(String url) {
//Array of Episode Objects
ArrayList<Implement> episodes = null;
try {
//Encode the URL into a URL Object
URL episode_feed_url = new URL(url);
//Open a Connection to the feed
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(episode_feed_url.openConnection().getInputStream(), null);
} finally {
}
int event_type = parser.getEventType();
Implement current_episode = null;
boolean done = false;
//Parse the feed, start reading throught the feed from top to bottom
while (event_type != XmlResourceParser.END_DOCUMENT && !done){
String tag_name = null;
switch (event_type){
//Found the start of the feed
case XmlResourceParser.START_DOCUMENT:
episodes = new ArrayList<Implement>();
break;
//Found a start tag
case XmlResourceParser.START_TAG:
//apply the data to our Episode object based on the tag name
tag_name = parser.getName();
Log.d("*********Current*********Tag*************", tag_name.toString());
if (tag_name.equalsIgnoreCase("item")){
current_episode = new Implement();
} else if (current_episode != null){
if (tag_name.equals("title")){
current_episode.setTitle(parser.nextText());
//Log.d("***********************DEBUG**************************",tag_name.toString( ));
} else if (tag_name.equals("pubDate")){
current_episode.setDate(parser.nextText());
//Log.d("***********************DEBUG**************************",tag_name.toString( ));
} else if (tag_name.equals("link")){
current_episode.setLink(parser.nextText());
//Log.d("***********************DEBUG**************************",tag_name.toString( ));
} else if (tag_name.equals("description")){
current_episode.setDescription(parser.nextText());
Log.d("*******************DESC*****************************",tag_name.toString( ));
}
}
break;
//An end tag has been reached
case XmlResourceParser.END_TAG:
tag_name = parser.getName();
//End of an Episode Item
if (tag_name.equalsIgnoreCase("item") && current_episode != null){
episodes.add(current_episode);
//Reached the end of all episodes, no more data to collect
} else if (tag_name.equalsIgnoreCase("channel")){
done = true;
}
break;
}
event_type = parser.next();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
//Return the Episode Array
return episodes;
}
}
This class is used for manipulating parsed data:
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class Implement {
//Episode data properties
private String title;
private String date;
private URL link;
private String imglink;
private String description;
//Getters and Setters for data
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setDate(String date) {
this.date = date;
Log.d("*******date*********", date.toString());
}
public String getDate() {
return date;
}
public void setLink(String link) {
try {
this.link = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public URL getLink() {
return link;
}
public void setDescription(String description) {
this.description = description;
//parse description for any image or video links
if (description.contains("<img ")){
String img = description.substring(description.indexOf("<img "));
String cleanUp = img.substring(0, img.indexOf(">")+1);
img = img.substring(img.indexOf("src=") + 5);
int indexOf = img.indexOf("'");
if (indexOf==-1){
indexOf = img.indexOf("\"");
}
img = img.substring(0, indexOf);
setImage(img);
this.description = this.description.replace(cleanUp, "");
}
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
public void setImage(String link) {
this.imglink = new String(link);
Log.d("*******image*********", imglink.toString());
}
public String getImage() {
return imglink;
}
}
And at last we display fetched data in listview
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class paper extends Activity implements OnItemClickListener {
//RSS Feed URL
private final String CGR_FEED_URL = "http://gdata.youtube.com/feeds/videos?author=JimmyRcom&orderby=updated&alt=rss&racy=include";
//XML Widgets
private ListView listview_episodes;
private ProgressBar progress_bar;
//Arrays of Episode Data
public static ArrayList<String> episode_titles;
private ArrayList<String> episode_dates;
private ArrayList<URL> episode_link;
private ArrayList<String> episode_image;
ImageAdapter adapter;
WebView mwebview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newyorktimes);
//XML Widgets by ID
// Log.d("****Value**of**String****", mStrings.toString());
mwebview=(WebView)findViewById(R.id.webview);
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.setVisibility(View.GONE);
listview_episodes = (ListView) findViewById(R.id.listview_episodes);
listview_episodes.setOnItemClickListener(this);
progress_bar = (ProgressBar) findViewById(R.id.progress_bar);
//Make Progress Bar Invisible
progress_bar.setVisibility(ProgressBar.INVISIBLE);
//Initialise Arrays
episode_titles = new ArrayList<String>();
episode_dates = new ArrayList<String>();
episode_link = new ArrayList<URL>();
episode_image=new ArrayList<String>();
downloadEpisodes(CGR_FEED_URL);
}
private void downloadEpisodes(String Url) {
//Make Progress Bar Visible While Downloading Feed
progress_bar.setVisibility(ProgressBar.VISIBLE);
Log.d("CGRParser", "Downloading Feed");
//Start an ASync Thread to take care of Downloading Feed
new DownloadEpisodes().execute(Url);
}
public class DownloadEpisodes extends AsyncTask<String, Integer, ArrayList<Implement>> {
@Override
protected ArrayList<Implement> doInBackground(String... url) {
//Download and Parse Feed
XmlFeedParser parser = new XmlFeedParser();
ArrayList<Implement> episodes = new ArrayList<Implement>();
episodes = parser.parse(url[0]);
return episodes;
}
@Override
protected void onPostExecute(ArrayList<Implement> result) {
//Feed has been Downloaded and Parsed, Display Data to User
Log.d("CGRParser", "Feed Download Complete");
displayEpisodes(result);
}
}
private void displayEpisodes(ArrayList<Implement> episodes) {
//Create String Arrays to seperate titles and dates
Log.d("CGRParser", "Displaying Episode Titles To User");
ArrayList<String> episode_titles = new ArrayList<String>();
ArrayList<String> episode_dates = new ArrayList<String>();
ArrayList<URL> episode_link = new ArrayList<URL>();
ArrayList<String>episode_image=new ArrayList<String>();
for (Implement episode : episodes) {
Log.d("CGRParser", "Episode Title: " + episode.getTitle());
episode_titles.add(episode.getTitle());
episode_dates.add(episode.getDate());
episode_link.add(episode.getLink());
episode_image.add(episode.getImage());
//System.out.println("size of episode_image" + episode.getImage());
}
this.episode_titles = episode_titles;
this.episode_dates = episode_dates;
this.episode_link= episode_link;
this.episode_image=episode_image;
if(episode_image.size() >0)
{
String mStrings[] = new String[episode_image.size()];
mStrings = episode_image.toArray(mStrings);
adapter=new ImageAdapter(this, mStrings,episode_titles);
listview_episodes.setAdapter(adapter);
for(int i=0;i<episode_image.size();i++)
Log.d("Value of mString", mStrings[i].toString());
}
// System.out.println("mstring"+mStrings[0].toString());
Log.d("Value of Episode_image", episode_image.toString());
Log.d("Value of Episode title", episode_titles.toString());
//Create a ListAdapter to Display the Titles in the ListView
ListAdapter adapter = new ArrayAdapter<String>(Technical.this, R.layout.episode_row, R.id.title, episode_titles);
listview_episodes.setAdapter(adapter);
//Set Progress Bar Invisible since we are done with it
progress_bar.setVisibility(ProgressBar.INVISIBLE);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Display the Title and Date to the user when they click on an episode
Toast.makeText(this, episode_titles.get(position) + ": " + episode_dates.get(position)+":"
+episode_link.get(position)+":"+episode_image.get(position), Toast.LENGTH_LONG).show();
mwebview.loadUrl(episode_link.get(position).toString());
//mwebview.setVisibility(View.VISIBLE);
//setContentView(R.layout.webview);
}
}
Xml that has been used in the project:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/relativeLayout1"
android:background="#483d8b"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:id="@+id/webview"
android:visible="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RelativeLayout android:layout_height="wrap_content"
android:id="@+id/relativeLayout2" android:layout_alignParentTop="true"
android:layout_width="fill_parent" >
<ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_alignParentLeft="true" android:id="@+id/progress_bar"></ProgressBar>
</RelativeLayout>
<LinearLayout android:layout_alignParentBottom="true"
android:id="@+id/list_holder" android:layout_below="@+id/relativeLayout2"
android:layout_height="fill_parent" android:layout_width="fill_parent">
<ListView android:id="@+id/listview_episodes"
android:layout_height="fill_parent"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
</RelativeLayout>
This xml is used to display in listview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:layout_toRightOf="@+id/icon"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/icon"
android:layout_alignBottom="@+id/icon"
android:layout_width="fill_parent"
android:gravity="center_vertical"
android:textColor="#ffffff"
android:textSize="16sp"
android:layout_marginLeft="10dip"
android:id="@+id/title"></TextView>
</LinearLayout>
from obove xml file.Which one is the "newyorktimes" files.
ReplyDeletexml files display.and please display the data for the Manifest file >which activity should first call
This code is not working ..
ReplyDelete1)two xml files but in above code define only one.
2)data ImageAdapter class ?
3)videolink that display didn't exist..
so save time find next.
Read properly Satya there are two xml already i have maintained. This is complete working code.Even u have any problem then tell me in details
ReplyDeleteThanks for fast response..
ReplyDeleteDude two xml; I knew but into coding you used only one
like
1)setContentView(R.layout.newyorktimes);
what is for your listview.
2)share your Manifestfile so we know that which Activity run first
3) Mention into above comment
you used "ImageAdapter" where you defined it dude..
if possible share your code so we can understand it better.
waiting for your...
I have sent you a simple project go through that .But tell me exactly what problem you are getting..
DeleteDo properly Best of Luck.........
hi..
Deletei want to implement this module as one part of my application and i face same problem which is face by satya shah.. can u help me???
Hi Dilip,
ReplyDeleteCan you help me with my problem - I am stuck up badly in rss xml parsing. I have asked the question with code at http://stackoverflow.com/questions/13136650/android-xmlpullparser-rss-feed-fail-to-fetch-all-entry-and-all-details
Look forward for a helping hand from you.
Thanks