RSS channel feed not showing feed data - android

actually in my app i want to do rss parsing. but when i parse data ts not giving me the response.
i have some problem with rss parser in my app.
i have put all my code and my rss data.
i tried many times but it will not giving me any data
and return listsize=0
my RSS channel data
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="/css/ticketekCore.css" ?>
<?xml-stylesheet type="text/css" href="/css/ticketekPageLayouts.css" ?>
<rss version="2.0">
<channel>
<title>Ticketek Event Listing</title>
<link>http://www.ticketek.com.au/</link>
<description>Ticketek Event Listing</description>
<language>en-au</language>
<item>
<title><![CDATA[The 2016 Cranston Cup Theatresports Grand Final]]></title>
<link>http://premier.ticketek.com.au/shows/show.aspx?sh=TSCRANST16</link>
<guid isPermaLink="true">http://premier.ticketek.com.au/shows/show.aspx?sh=TSCRANST16</guid>
<description><![CDATA[
<div class=" clearfix">
<div class="resultContainer">
<div class="contentImage">
<img src="//d35kvm5iuwjt9t.cloudfront.net/dbimages/sfx161301.jpg" style="width:61px;height:61px;" alt="The 2016 Cranston Cup Theatresports Grand Final" />
</div>
<div class="contentEvent">
<h6>
The 2016 Cranston Cup Theatresports Grand Final
</h6>
</div>
<div class="contentEventAndDate clearfix">
<div class="contentLocation">
<strong>Enmore Theatre</strong><br />
NSW/ACT
</div>
<div class="contentDate"> Sun 27 Nov 2016 </div>
<div class="resultBuyNow">
<a class="yellowGradientButton" href="/shows/show.aspx?sh=TSCRANST16&v=NMO">Get Tickets</a>
</div>
</div>
</div>
</div>
]]></description>
</item>
My java code:
Fragment.java
private class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
pDialog = (RelativeLayout) ll.findViewById(R.id.progressBarHolder);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
String weburl = RssFragment.this.getArguments().getString(MainActivity.DATA);
URL rssUrl = new URL(weburl);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView listview = (ListView) ll.findViewById(R.id.list);
if (myRssFeed != null) {
int size = myRssFeed.getList().size();
Log.d("listsize", String.valueOf(size));
MyCustomAdapter adapter = new MyCustomAdapter(mAct, R.layout.fragment_rss_row, myRssFeed.getList());
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Intent intent = new Intent(mAct,
RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate", myRssFeed.getItem(position).getPubdate());
bundle.putString("keyThumbnail", myRssFeed.getItem(position).getThumburl());
bundle.putString("keyVideo", myRssFeed.getItem(position).getVideourl());
bundle.putString("keyAudio", myRssFeed.getItem(position).getAudiourl());
intent.putExtras(bundle);
startActivity(intent);
}
});
} else {
String url = RssFragment.this.getArguments().getString(MainActivity.DATA);
String message = null;
if (!url.startsWith("http"))
message = "Debug info: '" + url + "' is most likely not a valid RSS url. Make sure the url entered in your configuration starts with 'http' and verify if it's valid XML using https://validator.w3.org/feed/";
Helper.noConnection(mAct, true, message);
}
if (pDialog.getVisibility() == View.VISIBLE) {
pDialog.setVisibility(View.GONE);
//feedListView.setVisibility(View.VISIBLE);
Helper.revealView(listview,ll);
}
super.onPostExecute(result);
}
}
my RSShandler class
package com.sherdle.universal.rss;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.text.Html;
/**
* This class is used to help us get the right information from the data from the feed.
*/
public class RSSHandler extends DefaultHandler {
private State currentState = State.unknown;
private RSSFeed feed;
private RSSItem item;
private boolean itemFound = false;
private StringBuilder tagContent;
public RSSHandler() {
}
#Override
public void startDocument() throws SAXException {
feed = new RSSFeed();
item = new RSSItem();
}
#Override
public void startElement(final String uri, final String localName, final String qName, final Attributes attributes)
throws SAXException {
currentState = State.unknown;
tagContent = new StringBuilder();
if (localName.equalsIgnoreCase("item") || localName.equalsIgnoreCase("entry")) {
itemFound = true;
item = new RSSItem();
currentState = State.unknown;
} else if (qName.equalsIgnoreCase("title")) {
currentState = State.title;
} else if (qName.equalsIgnoreCase("description") || qName.equalsIgnoreCase("content:encoded")) {
currentState = State.description;
} else if (qName.equalsIgnoreCase("link") || qName.equalsIgnoreCase("origLink")) {
currentState = State.link;
} else if (qName.equalsIgnoreCase("pubdate") || qName.equalsIgnoreCase("published")) {
currentState = State.pubdate;
} else if (qName.equalsIgnoreCase("media:thumbnail")) {
currentState = State.media;
String attrValue = attributes.getValue("url");
item.setThumburl(attrValue);
} else if (qName.equalsIgnoreCase("media:content")){
currentState = State.media;
String attrValue = attributes.getValue("url");
if (attributes.getValue("type") == null || attributes == null){
return;
} else if (attributes.getValue("type").startsWith("image")){
item.setThumburl(attrValue);
} else if (attributes.getValue("type").startsWith("video")){
item.setVideourl(attrValue);
} else if (attributes.getValue("type").startsWith("audio")){
item.setAudiourl(attrValue);
}
} else if (qName.equalsIgnoreCase("enclosure")){
currentState = State.media;
String attrValue = attributes.getValue("url");
if (attributes.getValue("type").startsWith("image")){
item.setThumburl(attrValue);
} else if (attributes.getValue("type").startsWith("video")){
item.setVideourl(attrValue);
} else if (attributes.getValue("type").startsWith("audio")){
item.setAudiourl(attrValue);
}
}
}
#Override
public void endElement(final String uri, final String localName,
final String qName) throws SAXException {
if (localName.equalsIgnoreCase("item") || localName.equalsIgnoreCase("entry")) {
feed.addItem(item);
}
if (itemFound == true) {
// "item" tag found, it's item's parameter
switch (currentState) {
case title:
String title = Html.fromHtml(tagContent.toString().trim()).toString();
item.setTitle(Html.fromHtml(tagContent.toString().trim()).toString());
break;
case description:
String description = tagContent.toString();
item.setDescription(tagContent.toString());
//if thumburl not already set
if (item.getThumburl() == null || item.getThumburl() == ""){
String html = tagContent.toString();
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
String source = imgEle.attr("src");
item.setThumburl(source);
}
break;
case link:
String link =tagContent.toString();
item.setLink(tagContent.toString());
break;
case pubdate:
String pubdate =tagContent.toString();
item.setPubdate(tagContent.toString());
break;
case media:
break;
default:
break;
}
} else {
// not "item" tag found, it's feed's parameter
switch (currentState) {
case title:
feed.setTitle(tagContent.toString());
break;
case description:
feed.setDescription(tagContent.toString());
break;
case link:
feed.setLink(tagContent.toString());
break;
case pubdate:
feed.setPubdate(tagContent.toString());
break;
default:
break;
}
}
}
#Override
public void characters(final char[] ch, final int start, final int length)
throws SAXException {
tagContent.append(ch, start, length);
}
public RSSFeed getFeed() {
return feed;
}
public enum State {
unknown, title, description, link, pubdate, media
}
}

Related

read rss feed - android

I'm trying to develop a simple application that reads rss feeds from a certain URL and then displays the results in a list view.
Here is my rss reader, which is the main thing in the app:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssReader {
private String title = null;
private String link = null;
private String description = null;
private ArrayList<RssItem> posts = new ArrayList<RssItem>();
private Thread thread;
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public RssReader(String url) {
this.urlString = url;
}
public boolean getParsingComplete() {
return this.parsingComplete;
}
public ArrayList<RssItem> getPosts() {
return posts;
}
public void parseXML(XmlPullParser parser) {
int event;
try {
event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = parser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.END_TAG:
if (name.equals("title")) {
title = parser.getText();
} else if (name.equals("link")) {
link = parser.getText();
} else if (name.equals("description")) {
description = parser.getText();
}
break;
}
if(title != null && link != null && description != null) {
RssItem item = new RssItem(this.title,this.description,this.link);
posts.add(item);
this.title = this.description = this.link = null;
}
event = parser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML() {
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(
XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXML(myparser);
stream.close();
} catch (Exception e) {
} finally {
parsingComplete = true;
}
}
});
thread.start();
}
And here is my MainActivity:
package com.example.ynetrssproject;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.ListView;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity {
private ListView news;
private String rssUrl = "http://www.themarker.com/cmlink/1.144";
private ArrayList<RssItem> list;
private RssItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
news = (ListView) findViewById(R.id.news);
RssReader reader = new RssReader(rssUrl);
reader.fetchXML();
while(true) {
Log.d("Runnning", "Run");
if(reader.getParsingComplete()) {
list = reader.getPosts();
break;
}
}
adapter = new RssItemAdapter(this, R.layout.post_item_list, list);
news.setAdapter(adapter);
}
}
The problem is that everytime I call fetchXML, eventually it returns me an empty ArrayList. Therefore, my listview keeps being empty.
My adapter isn't such a big deal. It works fine. The problem is that I keep getting an empty array list from the object RssReader. I know this because I performed a little if statement at the end of the code just to check if the ArrayList is empty.
P.S I have tried with multiple RSS urls but none of them works.
Also, I added the permission of Internet in my manifest.
use SAXParser
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("link".equals(qName)) {
parsingLink = true;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
}else if ("title".equals(qName)) {
parsingTitle = false;
}else if ("link".equals(qName)) {
parsingLink = false;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
}else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
public class RssItem {
// item title
private String title;
// item link
private String link;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#Override
public String toString() {
return title;
}
}

Parsing CDATA in android RSS

I'm trying to make an ANDROID app that reads RSS feeds so I used this tutorial ( http://android-er.blogspot.com/2010/05/simple-rss-reader-ii-implement-with.html ) and implemented it to my own url rss feeder. But the description tag isn't being shown..mostly cz in the xml of the feeder the description tags are CDATA. how can i parse the description cdata in my rss??Thanks!
here is my RSSHandler code :
import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;
public class RSSHandler extends DefaultHandler {
final int state_unknown = 0;
final int state_title = 1;
final int state_description = 2;
final int state_link = 3;
final int state_pubdate = 4;
int currentState = state_unknown;
RSSFeed feed;
RSSItem item;
boolean itemFound = false;
RSSHandler(){
}
RSSFeed getFeed(){
return feed;
}
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
feed = new RSSFeed();
item = new RSSItem();
}
#Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
itemFound = true;
item = new RSSItem();
currentState = state_unknown;
}
else if (localName.equalsIgnoreCase("title")){
currentState = state_title;
}
else if (localName.equalsIgnoreCase("description")){
currentState = state_description;
}
else if (localName.equalsIgnoreCase("link")){
currentState = state_link;
}
else if (localName.equalsIgnoreCase("pubdate")){
currentState = state_pubdate;
}
else{
currentState = state_unknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
feed.addItem(item);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch,start,length);
if (itemFound==true){
// "item" tag found, it's item's parameter
switch(currentState){
case state_title:
item.setTitle(strCharacters);
break;
case state_description:
item.setDescription(strCharacters);
break;
case state_link:
item.setLink(strCharacters);
break;
case state_pubdate:
item.setPubdate(strCharacters);
break;
default:
break;
}
}
else{
// not "item" tag found, it's feed's parameter
switch(currentState){
case state_title:
feed.setTitle(strCharacters);
break;
case state_description:
feed.setDescription(strCharacters);
break;
case state_link:
feed.setLink(strCharacters);
break;
case state_pubdate:
feed.setPubdate(strCharacters);
break;
default:
break;
}
}
currentState = state_unknown;
}
and here is my RSSReader code :
public class AndroidRssReader extends ListActivity {
private RSSFeed myRssFeed = null;
//private ArrayList<RSSItem> myRssFeed = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
//URL rssUrl = new URL("http://www.gov.hk/en/about/rss/govhkrss.data.xml");
URL rssUrl = new URL("http://www.merehbi.com/online/index.php?option=com_content&view=category&layout=blog&id=58&Itemid=155&lang=ar&format=feed&type=rss");
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (myRssFeed!=null)
{
TextView feedTitle = (TextView)findViewById(R.id.feedtitle);
TextView feedDescribtion = (TextView)findViewById(R.id.feeddescribtion);
TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate);
TextView feedLink = (TextView)findViewById(R.id.feedlink);
feedTitle.setText(myRssFeed.getTitle());
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
ArrayAdapter<RSSItem> adapter =
new ArrayAdapter<RSSItem>(this,
android.R.layout.simple_list_item_1,myRssFeed.getList());
setListAdapter(adapter);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this,ShowDetails.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate", myRssFeed.getItem(position).getPubdate());
intent.putExtras(bundle);
startActivity(intent);
}
}
i use this tutorial and its codes
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
and change some code by this answer
https://stackoverflow.com/a/8489223/3636653
public static void main(String[] args) throws Exception {
File file = new File("data.xml");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("topic");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}

how to set data in textbox after sax parsing

i parse the xml file and all data will parsed but i dont understand how to set this data in textview ? give me some idea about that
public class GtuItemXMLHandler extends DefaultHandler {
Gtudownload gtudownload;
Questionpaper questionpaper;
// Show me the XML.
private String currentString = "";
private String charactersString = "";
private Branch branch;
private Year year;
private Semester semester;
private int branchCount = 0;
private int yearCount = 0;
private int semesterCount = 0;
// private ArrayList<Gtudownload> itemsList = new ArrayList<Gtudownload>();
//
// public ArrayList<Gtudownload> getItemsList() {
// return itemsList;
// }
public Gtudownload getGtudownload(){
return this.gtudownload;
}
public Questionpaper getQuestionpaper()
{
return this.questionpaper;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i("GTU ", localName);
if (localName.equalsIgnoreCase("Gtudownload")) {
gtudownload = new Gtudownload();
currentString = "Gtudownload";
} else if (localName.equalsIgnoreCase("Questionpaper")) {
gtudownload.setQuestionpaper(new Questionpaper());
gtudownload.getQuestionpaper().setBranchList(new ArrayList<Branch>());
currentString = "Questionpaper";
} else if (localName.equalsIgnoreCase("Branch")) {
branch = new Branch();
gtudownload.getQuestionpaper().getBranchList().add(branch);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).setYearList(new ArrayList<Year>());
currentString = "Branch";
Log.i("Branch", attributes.getValue("value"));
branch.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("Year")) {
year = new Year();
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().add(year);
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).setSemesterList(new ArrayList<Semester>());
currentString = "Year";
Log.i("Year ", attributes.getValue("value"));
year.setValue(attributes.getValue("value"));
} else if (localName.equalsIgnoreCase("semester")) {
semester = new Semester();
currentString = "semester";
Log.i("Semester ", attributes.getValue("value"));
semester.setValue(attributes.getValue("value"));
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().add(semester);
} else if (localName.equalsIgnoreCase("url")){
currentString = "url";
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("Questionpaper")){
branchCount=0;
}else if(localName.equalsIgnoreCase("Branch")){
yearCount = 0;
branchCount++;
}else if(localName.equalsIgnoreCase("Year")){
semesterCount = 0;
yearCount++;
}else if(localName.equalsIgnoreCase("semester")){
semesterCount++;
}else if(localName.equalsIgnoreCase("url")){
gtudownload.getQuestionpaper().getBranchList().get(branchCount).getYearList().get(yearCount).getSemesterList().get(semesterCount).setUrl(charactersString);
Log.i("URL", charactersString);
}
currentString = "";
charactersString= "";
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
charactersString = new String(ch, start, length);
charactersString = charactersString.trim();
}
}
this is my activity and how can i set this parsing data in into textview
public class GtudldActivity extends Activity {
/** Called when the activity is first created. */
private TextView xmlOutput;
TextView example[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
xmlOutput = (TextView) findViewById(R.id.xmlOutput);
Gtudownload gtudownload = parseXML();
}
private Gtudownload parseXML() {
Gtudownload gtudownload = null;
try {
Log.w("AndroidParseXMLActivity", "Start");
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
GtuItemXMLHandler myXMLHandler = new GtuItemXMLHandler();
xr.setContentHandler(myXMLHandler);
InputSource is = new InputSource(getResources().openRawResource(R.raw.mgtu));
gtudownload = myXMLHandler.getGtudownload();
Log.i("Data",gtudownload+"");
xr.parse(is);
} catch (Exception e) {
Log.w("AndroidParseXMLActivity", e);
}
//xmlOutput.setText(gtudownload.toString());
return gtudownload;
}
}
You'll get so many examples for this on google. I am showing you one of the. Just try this
I hope it may help you. If you've any doubt, just post it here

Parse XML on Android

I am trying to use the API for our billing system in an Android Application, but I am having trouble figuring out how to parse the XML that it returns. Here is what my function looks like thus far...
public void ParseData(String xmlData)
{
try
{
// Document Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
// Input Stream
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlData));
// Parse Document into a NodeList
Document doc = db.parse(inStream);
NodeList nodes = doc.getElementsByTagName("ticket");
// Loop NodeList and Retrieve Element Data
for(int i = 0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
if (node instanceof Element)
{
Element child = (Element)node;
String id = child.getAttribute("id");
}
}
}
catch(SAXException e)
{
}
}
and here is what the XML data looks like that is returned. I need to loop through each and pull each element out, but I cant figure out how to do that with the DOM parser.
<whmcsapi>
<action>gettickets</action>
<result>success</result>
<totalresults>1</totalresults>
<startnumber>0</startnumber>
<numreturned>1</numreturned>
<tickets>
<ticket>
<id>1</id>
<tid>557168</tid>
<deptid>1</deptid>
<userid>1</userid>
<name><![CDATA[Array]]></name>
<email></email>
<cc></cc>
<c>TmDEga5v</c>
<date>2009-08-03 23:14:32</date>
<subject><![CDATA[Test Ticket]]></subject>
<message><![CDATA[This is a test ticket>
----------------------------
IP Address: xxx.xxx.xxx.xxx]]></message>
<status>Open</status>
<priority>Medium</priority>
<admin></admin>
<attachment></attachment>
<lastreply>2009-08-04 12:14:18</lastreply>
<flag>0</flag>
<service></service>
</ticket>
</tickets>
</whmcsapi>
Yes SAX parser is the solution and here is the basic code to get you started:
void parseExampleFunction(){
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
File myFile = new File( //the XML file which you need to parse );
myFile.createNewFile();
FileInputStream fOut = new FileInputStream(myFile);
BufferedInputStream bos = new BufferedInputStream( fOut );
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MessagesXMLHandler myXMLHandler = new MessagesXMLHandler(context);
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(bos));
}
// the class where the parsing logic needs to defined.This preferably can be in a different .java file
public class MessagesXMLHandler extends DefaultHandler{
//this function is called automatically when a start tag is encountered
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException
//variable localName is the name of the tag
//this function is called autiomatically when an end tag is encountered
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
}
//this function gets called to return the value stored betweeen the closing and opening tags
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
//now variable value has the value stored between the closing and opening tags
String value=new String(ch,start,length);
}
}
for parse xml on android best way is to use SAXParser. i explained it bellow with demo....
first of all create your activity class like as bellw.
public class ActivityForSax extends ListActivity {
private ProgressDialog pDialog;
private ItemXMLHandler myXMLHandler;
private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
private TextView textview;
private ListView mListView;
private ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_dom);
textview = (TextView)findViewById(R.id.textView1);
doParsing();
mListView = getListView();
}
public void doParsing(){
if (isNetworkAvailable()) {
textview.setText("Loading...Please wait...");
new AsyncData().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}
class AsyncData extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
menuItems = new ArrayList<HashMap<String, String>>();
pDialog = new ProgressDialog(ActivityForSax.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new ItemXMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
} catch (ParserConfigurationException pce) {
Log.e("SAX XML", "sax parse error", pce);
} catch (SAXException se) {
Log.e("SAX XML", "sax error", se);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
textview.setText("Done!!!");
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayList<Bean> itemsList = myXMLHandler.getItemsList();
for (int i = 0; i < itemsList.size(); i++) {
Bean objBean = itemsList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("TITLE :: ", objBean.getTitle());
map.put("DESC :: ", objBean.getDesc());
map.put("PUBDATE :: ", objBean.getPubDate());
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(ActivityForSax.this, menuItems,
R.layout.list_item,
new String[] { "TITLE :: ", "DESC :: ", "PUBDATE :: " }, new int[] {
R.id.name, R.id.email, R.id.mobile });
mListView.setAdapter(adapter);
}
}
public void showToast(String msg) {
Toast.makeText(ActivityForSax.this, msg, Toast.LENGTH_LONG).show();
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
now you need to create default handler class for parsing xml data.
public class ItemXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = "";
Bean item = null;
private ArrayList<Bean> itemsList = new ArrayList<Bean>();
public ArrayList<Bean> getItemsList() {
return itemsList;
}
// Called when tag starts
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
currentValue = "";
if (localName.equals("item")) {
item = new Bean();
}
}
// Called when tag closing
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equals("id")) {
item.setId(currentValue);
} else if (localName.equals("title")) {
item.setTitle(currentValue);
} else if (localName.equals("desc")) {
item.setDesc(currentValue);
} else if (localName.equals("pubDate")) {
item.setPubDate(currentValue);
} else if (localName.equals("link")) {
item.setLink(currentValue);
} else if (localName.equals("item")) {
itemsList.add(item);
}
}
// Called to get tag characters
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}
and finally your Bean class like as...
public class Bean {
private String id;
private String title;
private String desc;
private String pubDate;
private String link;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
Add java-json.jar in library folder
Compile files ('libs/java-json.jar') //add this line into your build
Here is the code to convert xml response to json response:
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(response.toString());
} catch (JSONException e) {
Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}

How to Build a RSS reader for Android?

I am new to android and i am trying to build a RSS reader for Android. I have built all the classes and XML files but its not giving the required output. Its just showing the message
No RSS feed available.
Please can some one suggest what should i do.
Here is the code which i took from the tutorial and tried to manipulate-
public final String RSSFEEDOFCHOICE = "http://blog.01synergy.com/feed/";
public final String tag = "RSSReader";
private RSSFeed feed = null;
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// go get our feed!
feed = getFeed(RSSFEEDOFCHOICE);
// display UI
UpdateDisplay();
}
private RSSFeed getFeed(String urlToRssFeed)
{
try
{
// setup the url
URL url = new URL(urlToRssFeed);
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
RSSHandler theRssHandler = new RSSHandler();
// assign our handler
xmlreader.setContentHandler(theRssHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
return theRssHandler.getFeed();
}
catch (Exception ee)
{
// if we have a problem, simply return null
return null;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(0,0,0, "Choose RSS Feed");
menu.add(0,1,0, "Refresh");
Log.i(tag,"onCreateOptionsMenu");
return true;
}
public boolean onOptionsItemSelected(Menu item){
switch (((View) item).getId()) {
case 0:
Log.i(tag,"Set RSS Feed");
return true;
case 1:
Log.i(tag,"Refreshing RSS Feed");
return true;
}
return false;
}
private void UpdateDisplay()
{
TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate);
ListView itemlist = (ListView) findViewById(R.id.itemlist);
if (feed == null)
{
feedtitle.setText("No RSS Feed Available");
return;
}
feedtitle.setText(feed.getTitle());
feedpubdate.setText(feed.getPubDate());
ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems());
itemlist.setAdapter(adapter);
itemlist.setOnItemClickListener(this);
itemlist.setSelection(0);
}
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
startSubActivity(itemintent,0);
}
private void startSubActivity(Intent itemintent, int i) {
// TODO Auto-generated method stub
}
}
This is my first approach to RSS Reader, It's no so dynamic and has boilerplate code but worked well for myself.
Usage:
RssParser parser = new RssParser(feedUrl);
Log.i("LOG", "Description: " + parser.getItem(3).description); //4th item's description
Class:
package com.uncocoder.course.app.feed_reader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class RssParser extends DefaultHandler {
private StringBuilder content;
private boolean inChannel;
private boolean inImage;
private boolean inItem;
private ArrayList<Item> items = new ArrayList<Item>();
private Channel channel = new Channel();
private Item lastItem;
public RssParser(String url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(url);
xr.setContentHandler(this);
xr.parse(new InputSource(sourceUrl.openStream()));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Item {
public String title;
public String description;
public String link;
public String category;
public String pubDate;
public String guid;
}
public class Channel {
public String title;
public String description;
public String link;
public String lastBuildDate;
public String generator;
public String imageUrl;
public String imageTitle;
public String imageLink;
public String imageWidth;
public String imageHeight;
public String imageDescription;
public String language;
public String copyright;
public String pubDate;
public String category;
public String ttl;
}
#Override
public void startDocument() throws SAXException {
Log.i("LOG", "StartDocument");
}
#Override
public void endDocument() throws SAXException {
Log.i("LOG", "EndDocument");
}
#Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = true;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = true;
}
if (localName.equalsIgnoreCase("item")) {
lastItem = new Item();
items.add(lastItem);
inItem = true;
}
content = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("image")) {
inImage = false;
}
if (localName.equalsIgnoreCase("channel")) {
inChannel = false;
}
if (localName.equalsIgnoreCase("item")) {
inItem = false;
}
if (localName.equalsIgnoreCase("title")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.title = content.toString();
} else if (inImage) {
channel.imageTitle = content.toString();
} else if (inChannel) {
channel.title = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("description")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.description = content.toString();
} else if (inImage) {
channel.imageDescription = content.toString();
} else if (inChannel) {
channel.description = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("link")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.link = content.toString();
} else if (inImage) {
channel.imageLink = content.toString();
} else if (inChannel) {
channel.link = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("category")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.category = content.toString();
} else if (inChannel) {
channel.category = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("pubDate")) {
if (content == null) {
return;
}
if (inItem) {
lastItem.pubDate = content.toString();
} else if (inChannel) {
channel.pubDate = content.toString();
}
content = null;
}
if (localName.equalsIgnoreCase("guid")) {
if (content == null) {
return;
}
lastItem.guid = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("url")) {
if (content == null) {
return;
}
channel.imageUrl = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("width")) {
if (content == null) {
return;
}
channel.imageWidth = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("height")) {
if (content == null) {
return;
}
channel.imageHeight = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("language")) {
if (content == null) {
return;
}
channel.language = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("copyright")) {
if (content == null) {
return;
}
channel.copyright = content.toString();
content = null;
}
if (localName.equalsIgnoreCase("ttl")) {
if (content == null) {
return;
}
channel.ttl = content.toString();
content = null;
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (content == null) {
return;
}
content.append(ch, start, length);
}
public Item getItem(int index) {
return items.get(index);
}
}
Check following link, It's open source RSS reader for Android, You can download code for reference
http://code.google.com/p/android-rss/
There is a tutorial (including complete source code) on how to build an Android RSS reder here:
part 1 (complete application)
part 2 (application updated to parse image tags from desciption)
part 3 (application update with Android 3.0)
The tutorial uses SAX parser and includes a complete Android project that accesses an RSS feed and then displays the feed in a list view.
There still seems to be a lot of people interested in this - so if you are looking for an Android 3.0+ with fragments/async tasks etc, as well as complete application code, I have updated the posts again, and they can be found here!
You can download and check my project on google-play.
This project is about some turkish sport channels feeds. Lots of channels are in one application.
You can check source code of project on github.
Parse this type of Rss Feeds easily using XmlPullParser
public class RSSParser {
public static ArrayList<Pojo> getParserData(String Data){
try {
RSSXMLTag currentTag = null;
ArrayList<Pojo> postDataList = new ArrayList<>();
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(Data));
int eventType = xpp.getEventType();
Pojo pdData = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEEE, DD MMM yyyy ");
while (eventType != XmlPullParser.END_DOCUMENT) {
int i = 0;
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
pdData = new Pojo();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
} else if (xpp.getName().equals("creator")) {
currentTag = RSSXMLTag.CREATOR;
} else if (xpp.getName().equals("category")) {
currentTag = RSSXMLTag.CATEGORY;
} else if (xpp.getName().equals("description")) {
currentTag = RSSXMLTag.DESCRIPTION;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
Date postDate = dateFormat.parse(pdData.postDate);
pdData.postDate = dateFormat.format(postDate);
postDataList.add(pdData);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("debug", content);
if (pdData != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (pdData.postTitle != null) {
pdData.postTitle += content;
} else {
pdData.postTitle = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (pdData.postLink != null) {
pdData.postLink += content;
} else {
pdData.postLink = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (pdData.postDate != null) {
pdData.postDate += content;
} else {
pdData.postDate = content;
}
}
break;
case CATEGORY:
if (content.length() != 0) {
if (pdData.postCategory != null) {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
} else {
i = i + 1;
if (i == 1) {
pdData.postCategory = content;
}
}
}
break;
case DESCRIPTION:
if (content.length() != 0) {
if (pdData.postDescription != null) {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription += string;
} else {
String s = content;
String string = s.substring(s.indexOf("src=\"") + 5, s.indexOf("\" class=\""));
pdData.postDescription = string;
}
}
break;
case CREATOR:
if (content.length() != 0) {
if (pdData.postCreator != null) {
pdData.postCreator += content;
} else {
pdData.postCreator = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
return postDataList;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public enum RSSXMLTag {
IGNORETAG, TITLE, LINK, DATE,CREATOR,CATEGORY, DESCRIPTION;
}
public class Pojo {
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostLink() {
return postLink;
}
public void setPostLink(String postLink) {
this.postLink = postLink;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostCategory() {
return postCategory;
}
public void setPostCategory(String postCategory) {
this.postCategory = postCategory;
}
public String getPostDescription() {
return postDescription;
}
public void setPostDescription(String postDescription) {
this.postDescription = postDescription;
}
public String getPostCreator() {
return postCreator;
}
public void setPostCreator(String postCreator) {
this.postCreator = postCreator;
}
public String postTitle;
public String postLink;
public String postDate;
public String postCategory;
public String postDescription;
public String postCreator;
}
}

Categories

Resources