Wednesday, November 20, 2013
Android XML parsing using XMLPull Parser (RSS Feed)
Manchu Bhargavi
4:21 AM
android rss
,
android rss parser
,
android rss parser with asynctask
,
android xml parsing
,
feed
,
parser rss
,
rss
,
rss asynctask
,
rss parser in android
,
xmlpullparser
10 comments
:
Hi,
This is good example for parse the Rss feed with Asynctask with baseadapter in Android.Now let us see about RSS
Intro about RSS:
What RSS Is Being Used for:
1.create a project called feed. and create a xml file
activtiy_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000">
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFAF0" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Techgig News"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
</RelativeLayout>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:background="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
android:divider="@null"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:listSelector="@android:color/transparent" >
</ListView>
</LinearLayout>
2.create the Feed class.It is used to create getter and setter method
Feed.java :
package com.example.feed;
public class Feed {
private String text;
private String title,links,desc,image_list,pub_date,item;
private int id;
public String getText() {
return text;
}
public String getTitle() {
return title;
}
public String getLinks() {
return links;
}
public String getDesc() {
return desc;
}
public String getImage_list() {
return image_list;
}
public String getPub_date() {
return pub_date;
}
public String getItem() {
return item;
}
public int getId() {
return id;
}
public void setText(String text) {
this.text = text;
}
public void setTitle(String title) {
this.title = title;
}
public void setLinks(String links) {
this.links = links;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setImage_list(String image_list) {
this.image_list = image_list;
//parse description for any image or video links
}
public void setPub_date(String pub_date) {
this.pub_date = pub_date;
}
public void setItem(String item) {
this.item = item;
}
public void setId(int id) {
this.id = id;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return "Title/n"+title+ "Links/n"+links+"Image_url/n"+image_list;
}
}
4.Here the output shown below
This is good example for parse the Rss feed with Asynctask with baseadapter in Android.Now let us see about RSS
Intro about RSS:
What is RSS?
RSS, which stands for Really Simple Syndication or Rich Site Summary, is a simple XML based format that allows anyone to easily share content on the web.
What RSS Is Being Used for:
Well-known Companies Using RSS
- Company News
- Latest Headlines
- Newsletters or Ezines
- Product Updates
- Special Announcements
- Job Adverts
- Press Releases
- Marketing Communications
- Service Upgrades
- E-courses
- Weblogs
There are many possibilities!
RSS as a publishing standard has been rapidly growing and is being widely adapted by most of the web publishers today.
Using RSS, publishers can easily make their content syndicated and thus drive more targeted traffic to their site or weblog.
Why Publishers Prefer RSS?
- Yahoo
- Amazon
- Forbes
- MSN
- BBC
- CNN
- CNET
In addition to these huge websites, thousands of small time webmasters and publishers are also making the use of RSS.
In this example how to parse the rss feed shown below
- RSS makes it easy for them to stay connected with their readers, members and clients and build lasting relationships.
- Making their web content syndicated, allows the publishers to provide regular updates - such as the latest information, new postings, relevant article previews etc through their RSS content.
- It's a brand new way of generating fresh content, driving targeted traffic and leveraging brand awareness. By publishing content through RSS, publishers can give other websites an opportunity to syndicate and use their content without any effort.
- Content enabled with RSS can be easily added to desktop or web-based RSS readers available online. Subscribers are able to keep track of their favorite content and get brief details about it.
An RSS file (also known as an RSS Feed or RSS Channel) contains specific headlines, summaries and links, which lead back to the actual content on the webpage.
1.create a project called feed. and create a xml file
activtiy_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000">
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFAF0" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Techgig News"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
</RelativeLayout>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:background="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
android:divider="@null"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:listSelector="@android:color/transparent" >
</ListView>
</LinearLayout>
2.create the Feed class.It is used to create getter and setter method
Feed.java :
package com.example.feed;
public class Feed {
private String text;
private String title,links,desc,image_list,pub_date,item;
private int id;
public String getText() {
return text;
}
public String getTitle() {
return title;
}
public String getLinks() {
return links;
}
public String getDesc() {
return desc;
}
public String getImage_list() {
return image_list;
}
public String getPub_date() {
return pub_date;
}
public String getItem() {
return item;
}
public int getId() {
return id;
}
public void setText(String text) {
this.text = text;
}
public void setTitle(String title) {
this.title = title;
}
public void setLinks(String links) {
this.links = links;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setImage_list(String image_list) {
this.image_list = image_list;
//parse description for any image or video links
}
public void setPub_date(String pub_date) {
this.pub_date = pub_date;
}
public void setItem(String item) {
this.item = item;
}
public void setId(int id) {
this.id = id;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return "Title/n"+title+ "Links/n"+links+"Image_url/n"+image_list;
}
}
3. create the FeedActivity.java class. It is used to parse the xml.please the add the Imageloader package to this project.
FeedActivity.java :
package com.example.feed;
import imageload.ImageLoader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import com.example.feed.MainActivity.RssFeedAsyncTask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class activity extends FeedActivity {
int loader;
ListView listView;
Context context;
String bgStr,imgurl;
String mediaUrl = null;
String tagname;
Intent i;
AlertDialogmethod alert;
public ArrayList<Feed> items;
ConnectionDetector cd;
Boolean isInternetPresent = false;
ArrayList<Feed> feeds = new ArrayList<Feed>();
public final Pattern PATTERN = Pattern.compile("<div.+?class=[\"'](.+?)[\"'].+?>");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
cd = new ConnectionDetector(getApplicationContext());
alert=new AlertDialogmethod();
loader=R.drawable.no_image;
listView = (ListView) findViewById(R.id.listView1);
listView.setVerticalScrollBarEnabled(false);
listView.setVerticalFadingEdgeEnabled(false);
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
new LoadFeed().execute("http://www.techgig.com/newsfeed");
}
else
{
alert.showAlertDialog(activity.this, "No internet connection available");
}
}
class LoadFeed extends AsyncTask<String, Void, ArrayList<Feed>>{
ProgressDialog dialog;
public LoadFeed() {
// TODO Auto-generated constructor stub
dialog = new ProgressDialog(activity.this);
dialog.setMessage("Loading...");
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}
@Override
protected ArrayList<Feed> doInBackground(String... arg0) {
ArrayList<Feed> feeds = new ArrayList<Feed>();
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(arg0[0]));
HttpResponse res = client.execute(method);
InputStream is = res.getEntity().getContent();
parser.setInput(new InputStreamReader(is));
// parser.setInput(new InputStreamReader(getUrlData("http://www.techgig.com/newsfeed")));
int eventType = parser.getEventType();
Feed feed = new Feed();
String text = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
tagname = parser.getName();
//Log.d(tagname, "tagname");
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("item")) {
feed = new Feed();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("item")) {
feeds.add(feed);
} else if (tagname.equalsIgnoreCase("title"))
{
feed.setTitle(text);
} else if (tagname.equalsIgnoreCase("description"))
{
feed.setDesc(text);
// Log.d("txt", text);
} else if (tagname.equalsIgnoreCase("link")) {
feed.setLinks(text);
}
else if(tagname.equalsIgnoreCase("thumbnail")){
feed.setImage_list(parser.getAttributeValue(null,"url"));
}
else if (tagname.equalsIgnoreCase("pubDate"))
{
feed.setPub_date(text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return feeds;
}
private String getMatch(String string, String text, int i) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(ArrayList<Feed> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
// Log.d("Array",result.toString());
/*ArrayAdapter<Feed> adapter =
new ArrayAdapter<Feed>(activity.this,android.R.layout.simple_list_item_1,result);*/
listView.setAdapter(new setadapter(activity.this,result));
}
public class setadapter extends BaseAdapter
{
public setadapter(Context context,ArrayList<Feed> feeds)
{
items = feeds;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageLoader imgloader=new ImageLoader(getApplicationContext());
LayoutInflater inflate=getLayoutInflater();
convertView=inflate.inflate(R.layout.list_adapter,null);
TextView tv=(TextView)convertView.findViewById(R.id.textView1);
TextView tv1=(TextView)convertView.findViewById(R.id.textView2);
ImageView iv=(ImageView)convertView.findViewById(R.id.imageView1);
tv.setText(items.get(position).getTitle());
//Log.d("info", items.get(position).toString());
//tv1.setText(items.get(position).getLinks());
//tv1.setText(Html.fromHtml(items.get(position).getDesc()));
//Log.d("image url ",items.get(position).getDesc());
//imgloader.DisplayImage(items.get(position).getImage_list(),loader, iv);
final String regex = "(?<=<img src=\")[^\"]*";
final Pattern p = Pattern.compile(regex);
final Matcher m = p.matcher(items.get(position).getDesc());
while (m.find())
{
Log.d("image list", m.group());
imgloader.DisplayImage(m.group(),loader, iv);
}
return convertView;
}
}
}
}
4.Here the output shown below
Subscribe to:
Post Comments
(
Atom
)
Hi, i am starting with Android, please help me.
ReplyDeleteWhere is the ImageLoader package?
Sorry my poor english, I am from Brazil.
Thanks
can I Have full source code of given Example
ReplyDeleteCan you send me the source code also..plz
Deleteyou rich with website my http://giaitri24hvn.blogspot.com/
ReplyDeletecan I Have full source code of given Example
ReplyDeletehttps://www.youtube.com/watch?v=9t1jvzDn05o&feature=autoshare
ReplyDeletewhat is this please explain
ReplyDeletepublic class activity extends FeedActivity {
It is really a great work and the way in which u r sharing the knowledge is excellent.
ReplyDeleteThanks for helping me to understand basic concepts. As a beginner in android programming your post help me a lot.Thanks for your informative article.
Android Training in velachery | Android Training institute in chennai
In this android XML coding and this content information is really great. We shared this knowledge really excellent. As a Beginner in this android programming, your post really helps and with my friend also.Selenium Training in Chennai | No.1 Selenium Training Institutes in Chennai | Best Selenium Training in Chennai | Android Training in Chennai with Placement
ReplyDeleteXML defines the best layout outlines for the android applications and thus each android developer should be acquainted with its usefulness. When we are insufficient of the information we need to develop our ideas, we should be visiting such sites. I have loved such approach to the analysis of this concept. Guide on how to write a good essay
ReplyDelete