Parsing CDATA in android RSS - android

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 "";
}

Related

RSS channel feed not showing feed data

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
}
}

Get images from rss feed

I'm trying to display the images of rss feed with Android Studio but I don't know how to do this. I can get all the other items but I don't know why I can't get the images. Can you help me please?
This is my Handler:
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;
final int state_enclosure = 5;
final int state_url = 6;
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("url")){
currentState = state_url;
}
//{
// if (!attributes.getValue("url").equalsIgnoreCase("null")) {
// feed.setImage(attributes.getValue("url"));
//} else {
// feed.setImage("");
//}
// currentState = state_image;
//}
else if (localName.equalsIgnoreCase("enclosure")){
currentState = state_enclosure;
}
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_url:
item.setUrl(strCharacters);
break;
case state_enclosure:
item.setEnclosure(strCharacters);
break;
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_url:
feed.setUrl(strCharacters);
break;
case state_enclosure:
feed.setEnclosure(strCharacters);
break;
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;
}
EDIT
how I show images
try {
URL url = new URL(web.get(position).getEnclosure()+web.get(position).getUrl());
HttpGet httpRequest;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
ImageView img = (ImageView) rowView.findViewById(R.id.enclosure);
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
ex.printStackTrace();
}
The code you've posted isn't really relevant to the problem, you should have already fetched the feed and parsed it to extract the urls, you can then do the following, however I would recommend Picasso from Square instead which will do all the heavy lifting AND add functionality like caching and interrupting requests automatically - http://square.github.io/picasso/
try {
InputStream inStream = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(inStream, "my source name");
return d;
} catch (Exception e) {
return null;
}

RSS Reader doesent fetch HTML Characters

The RSS Reader doesent fetch HTML Characters like "#8220;" so when the feed is "Hey#8220;" the App shows only "Hey" but i doesent know why. I tried things like Html.fromHtml, but it doesent work. Does anyone see the mistake?
Thanks for answers
`public class AndroidRssReader extends ListActivity {
private RSSFeed myRssFeed = null;
TextView feedTitle;
TextView feedDescribtion;
TextView feedPubdate;
TextView feedLink;
public class MyCustomAdapter extends ArrayAdapter<RSSItem> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem> list) {
super(context, textViewResourceId, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView listTitle=(TextView)row.findViewById(R.id.listtitle);
listTitle.setText(myRssFeed.getList().get(position).getTitle());
TextView listPubdate=(TextView)row.findViewById(R.id.listpubdate);
listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
if (position%2 == 0){
listTitle.setBackgroundColor(0xff101010);
listPubdate.setBackgroundColor(0xff101010);
}
else{
listTitle.setBackgroundColor(0xff080808);
listPubdate.setBackgroundColor(0xff080808);
}
return row;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
feedTitle = (TextView)findViewById(R.id.feedtitle);
feedDescribtion = (TextView)findViewById(R.id.feeddescribtion);
feedPubdate = (TextView)findViewById(R.id.feedpubdate);
feedLink = (TextView)findViewById(R.id.feedlink);
readRss();
}
private void readRss(){
feedTitle.setText("--- wait ---");
feedDescribtion.setText("");
feedPubdate.setText("");
feedLink.setText("");
setListAdapter(null);
Toast.makeText(this, "News werden geladen...", Toast.LENGTH_LONG).show();
try {
URL rssUrl = new URL("MYURL");
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (myRssFeed!=null)
{
Calendar c = Calendar.getInstance();
String strCurrentTiime = "\n(Time of Reading - "
+ c.get(Calendar.HOUR_OF_DAY)
+ " : "
+ c.get(Calendar.MINUTE) + ")\n";
feedTitle.setText(myRssFeed.getTitle() + strCurrentTiime);
feedDescribtion.setText(myRssFeed.getDescription());
feedPubdate.setText(myRssFeed.getPubdate());
feedLink.setText(myRssFeed.getLink());
MyCustomAdapter adapter =
new MyCustomAdapter(this, R.layout.row, myRssFeed.getList());
setListAdapter(adapter);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
/*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);*/
Uri feedUri = Uri.parse(myRssFeed.getItem(position).getLink());
Intent myIntent = new Intent(Intent.ACTION_VIEW, feedUri);
startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 0, 0, "Refresh");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case (0): readRss();
break;
default:
break;
}
return true;
}
}`
public class RSSFeed {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
private List<RSSItem> itemList;
RSSFeed(){
itemList = new Vector<RSSItem>(0);
}
void addItem(RSSItem item){
itemList.add(item);
}
RSSItem getItem(int location){
return itemList.get(location);
}
List<RSSItem> getList(){
return itemList;
}
void setTitle(String value)
{
title = value;
}
void setDescription(String value)
{
description = value;
}
void setLink(String value)
{
link = value;
}
void setPubdate(String value)
{
pubdate = value;
}
String getTitle()
{
return title;
}
String getDescription()
{
return description;
}
String getLink()
{
return link;
}
String getPubdate()
{
return pubdate;
}
}
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;
}
}
public class RSSItem {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
RSSItem(){
}
void setTitle(String value)
{
value.replace("#8220;", "hi");
title =value;
}
void setDescription(String value)
{
description = value;
}
void setLink(String value)
{
link = value;
}
void setPubdate(String value)
{
pubdate = value;
}
String getTitle()
{
return title;
}
String getDescription()
{
return description;
}
String getLink()
{
return link;
}
String getPubdate()
{
return pubdate;
}
/*#Override
public String toString() {
// TODO Auto-generated method stub
return title;
}*/
}
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
Set an encoding to your input source or stream. This sample code can help you.

parsing XML online file Android

I am making an application for Android and I need to display an XML file of this page:http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009
I tried the solutions given on the page but I find it wrong since it is not displayed when you run the application. I just want to show "tipo= DOLAR SPOT INTERCAMBIO"
This is the XML CODE
and this is my code:
xmlpruebaprueba.jar
XMLdataCollected sitesList= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlpruebaprueba);
//creando un Layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
//creando TextView
TextView Registro[];
TextView Tipo[];
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceURL = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=7009");
handlingXml HandlingXml = new handlingXml();
xr.setContentHandler(HandlingXml);
xr.parse(new InputSource(sourceURL.openStream()));
}catch (Exception e){
System.out.println("XML Parsing Exception= " + e);
}
sitesList = handlingXml.sitesList;
Registro = new TextView[sitesList.getRegistro().size()];
Tipo = new TextView[sitesList.getTipo().size()];
for (int i = 0; i < sitesList.getRegistro().size(); i++) {
Registro[i] = new TextView(this);
Registro[i].setText("Registro = "+sitesList.getRegistro().get(i));
Tipo[i] = new TextView(this);
Tipo[i].setText("Tipo = "+sitesList.getTipo().get(i));
layout.addView(Registro[i]);
layout.addView(Tipo[i]);
}
}
}
and this is my handler
Boolean currentElement = false;
String currentValue = null;
public static XMLdataCollected sitesList = null;
public static XMLdataCollected getDataCollected (){
return sitesList;
}
public static void setSitesList(XMLdataCollected sitesList){
handlingXml.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
currentElement = true;
if(localName.equals("Root"))
{
sitesList = new XMLdataCollected();
}else if (localName.equals("Registro")){
String attr = attributes.getValue("tipo");
sitesList.setTipo(attr);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
currentElement = false;
if (localName.equalsIgnoreCase("Registro"))
sitesList.setRegistro(currentValue);
else if (localName.equalsIgnoreCase("Root"))
sitesList.setRoot(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
and this is my dataCollected
public class XMLdataCollected {
private ArrayList<String> root = new ArrayList<String>();
private ArrayList<String> registro = new ArrayList<String>();
private ArrayList<String> tipo = new ArrayList<String>();
public ArrayList<String> getRoot (){
return root;
}
public void setRoot(String root){
this.root.add(root);
}
public ArrayList<String> getRegistro (){
return registro;
}
public void setRegistro(String registro){
this.registro.add(registro);
}
public ArrayList<String> getTipo (){
return tipo;
}
public void setTipo(String tipo){
this.tipo.add(tipo);
}
}
You are calling your Web Request on main UI thread.
PLEASE DO NOT DO THIS
use AsyncTask to call web your request.

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

Categories

Resources