I already made an Android RSS Feed App from Google Alerts Source. After I compiled and running only showing about half article or can't fetch all text from one source but not crash.
From RssAtomParseHandler.java
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.a.b.c.d.e.RssAtomItem;
public class RssAtomParseHandler extends DefaultHandler {
private List<RssAtomItem> rssItems;
// Used to reference item while parsing
private RssAtomItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// Parsing link indicator
private boolean parsingContents;
// A buffer for title contents
private StringBuffer currentTitleSb;
// A buffer for content tag contents
private StringBuffer currentContentSb;
public RssAtomParseHandler() {
rssItems = new ArrayList<RssAtomItem>();
}
public List<RssAtomItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("entry".equals(qName)) {
currentItem = new RssAtomItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
} else if ("content".equals(qName)) {
parsingContents = true;
currentContentSb = new StringBuffer();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("entry".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
if (currentItem != null) // There is a title tag for a whole channel present. It is being parsed before the entry tag is present, so we need to check if item is not null
currentItem.setTitle(currentTitleSb.toString());
} else if ("content".equals(qName)) {
parsingContents = false;
if (currentItem != null)
currentItem.setContent(currentContentSb.toString());
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentTitleSb.append(new String(ch, start, length));
} else if (parsingContents) {
if (currentItem != null)
currentContentSb.append(new String(ch, start, length));
}
} }
From RssAtomReader.java
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.a.b.c.d.e.RssAtomItem;
public class RssAtomReader {
private String rssUrl;
/**
* Constructor
*
* #param rssUrl
*/
public RssAtomReader(String rssUrl) {
this.rssUrl = rssUrl;
}
/**
* Get RSS items.
*
* #return
*/
public List<RssAtomItem> getItems() throws Exception {
// SAX parse RSS data
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssAtomParseHandler handler = new RssAtomParseHandler();
saxParser.parse(rssUrl, handler);
return handler.getItems();
} }
From activity_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/detailsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[POST TITLE GOES HERE]"
android:textAppearance="?android:attr/textAppearanceMedium" />
<WebView
android:id="#+id/detailsWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
How I can fix it so it will show ?
Related
I'am trying to parse an XML file from server, i fellowed this tutorial but I couldn't retrieve Data in activity either in Logcat!
It's showing a NullPointerException at this line
for(int i = 0; i < data.getTitle().size(); i++)
Based to the tutorial i don't know if I intialised the variable data correctly in the activity .
so This is my MainActivity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView title[];
TextView artist[];
TextView country[];
TextView company[];
TextView price[];
TextView year[];
public static XMLGettersSetters data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View layout = findViewById(R.id.layout);
for (int i = 0; i < data.getTitle().size(); i++) {
title[i] = new TextView(this);
title[i].setText("Title= " + data.getTitle().get(i));
artist[i] = new TextView(this);
artist[i].setText("Artist=" + data.getArtist().get(i));
company[i] = new TextView(this);
company[i].setText("Company=" + data.getCompany().get(i));
country[i] = new TextView(this);
country[i].setText("Country=" + data.getCountry().get(i));
price[i] = new TextView(this);
price[i].setText("Price=" + data.getPrice().get(i));
year[i] = new TextView(this);
year[i].setText("Year=" + data.getYear().get(i));
((ViewGroup) layout).addView(title[i]);
((ViewGroup) layout).addView(artist[i]);
((ViewGroup) layout).addView(company[i]);
((ViewGroup) layout).addView(country[i]);
((ViewGroup) layout).addView(price[i]);
((ViewGroup) layout).addView(year[i]);
}
}
}
XMLHandler class
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 java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class XMLHandler extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("CATALOG")) {
data = new XMLGettersSetters();
} else if (localName.equals("CD")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
// View layout = findViewById(R.id.layout);
} catch (Exception e) {
System.out.println(e);
}
}
}
/**
* This will be called when the tags of the XML end.
**/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("title"))
data.setTitle(elementValue);
else if (localName.equalsIgnoreCase("artist"))
data.setArtist(elementValue);
else if (localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
else if (localName.equalsIgnoreCase("company"))
data.setCompany(elementValue);
else if (localName.equalsIgnoreCase("price"))
data.setPrice(elementValue);
else if (localName.equalsIgnoreCase("year"))
data.setYear(elementValue);
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
XmlGettersSetters
import android.util.Log;
import java.util.ArrayList;
public class XMLGettersSetters {
//company
private ArrayList<String> company = new ArrayList<String>();
public ArrayList<String> getCompany() {
return company;
}
public void setCompany(String company) {
this.company.add(company);
Log.i("This is the company:", company);
}
//title
private ArrayList<String> title = new ArrayList<String>();
public ArrayList<String> getTitle() {
return title;
}
public void setTitle(String title) {
this.title.add(title);
Log.i("This is the title:", title);
}
//artist
private ArrayList<String> artist = new ArrayList<String>();
public ArrayList<String> getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist.add(artist);
Log.i("This is the artist:", artist);
}
//country
private ArrayList<String> country = new ArrayList<String>();
public ArrayList<String> getCountry() {
return country;
}
public void setCountry(String country) {
this.country.add(country);
Log.i("This is the country:", country);
}
//price
private ArrayList<String> price = new ArrayList<String>();
public ArrayList<String> getPrice() {
return price;
}
public void setPrice(String price) {
this.price.add(price);
Log.i("This is the price:", price);
}
//year
private ArrayList<String> year = new ArrayList<String>();
public ArrayList<String> getYear() {
return year;
}
public void setYear(String year) {
this.year.add(year);
Log.i("This is the Year:", year);
}
}
As far as I can tell, you never initialized the data field in MainActivity. Also, making it static seems like a bad idea. Java statics are almost always a bad idea unless you really know you need one.
URL url = new URL("https://www.setindia.com");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
// error on the last line please get me an explanation (new to android) and is this right
MAIN ACTIVITY:
package com.example.testparser;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
public static String TAG = "MYParser";
GettersSetters getData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
View layout = findViewById(R.id.layout);
TextView tittle[];
TextView country[];
XMLHandler xmlHandlerObject = null;
try{
Log.d(TAG, "try");
SAXParserFactory saxParserFactoryObject = SAXParserFactory.newInstance(); //obtain and configure a SAX based parser
SAXParser saxParserObject = saxParserFactoryObject.newSAXParser(); //obtaining object for SAX parser
XMLReader xmlReaderObject = saxParserObject.getXMLReader();
URL url = new URL("https://www.setindia.com/setindia_api/episode/1?date=22-10-2013&hd=1");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
Log.d(TAG, "about to get an error");
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
Log.d(TAG, "try end");
}
catch (Exception e) {
Log.e(TAG, e.getMessage());
}
Log.d(TAG, "OnCreate fetching the data from the xml");
getData = xmlHandlerObject.getXMLData();
tittle = new TextView[getData.getTittle().size()];
country = new TextView[getData.getCountry().size()];
for (int i = 0; i < getData.getTittle().size(); i++) {
tittle[i] = new TextView(this);
tittle[i].setText("ITEM is : " + getData.getTittle().get(i));
country[i] = new TextView(this);
country[i].setText("Country is :" + getData.getTittle().get(i));
((ViewGroup) layout).addView(tittle[i]);
((ViewGroup) layout).addView(country[i]);
setContentView(R.layout.main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
GettersSetters :
package com.example.testparser;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.util.Log;
public class GettersSetters {
private ArrayList<String> tittle = new ArrayList<String>();
private ArrayList<String> country = new ArrayList<String>();
public ArrayList<String> getCountry(){
return country;
}
public ArrayList<String> getTittle(){
return tittle;
}
public void setCountry(String country){
this.country.add(country);
Log.i("This is the country : ",country);
}
public void setTittle(String tittle){
this.tittle.add(tittle);
Log.i("This is the tittle : ",tittle);
}
}
XMLHandler:
package com.example.testparser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
public static String TAG = "MYParser";
public static GettersSetters data = null;
String elementValue = null ;
Boolean elementOn = false;
public GettersSetters getXMLData(){
Log.e(TAG, "getXMLdata -> "+data.toString());
return data;
}
public void setXMLData(GettersSetters data){
XMLHandler.data = data;
Log.e(TAG, "setXmldata");
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
elementOn = true;
Log.d(TAG, "Checking the first element"+localName.equalsIgnoreCase("item"));
if(localName.equalsIgnoreCase("item"))
{
Log.d(TAG, "Creating a new getter setter instance");
data = new GettersSetters();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(elementOn)
{
elementValue = new String(ch,start,length);
elementOn =false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
super.endElement(uri, localName, qName);
if(localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
if(localName.equalsIgnoreCase("tittle"))
data.setTittle(elementValue);
}
}
MAIN.Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SAGAR HERE"
android:textSize="20dp"
android:gravity="center_horizontal"
android:id="#+id/layout"
/>
</LinearLayout>
Don't do network operations on UI Thread (main).
You can use AsyncTask which enables proper and easy use of the UI thread. it allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers (It uses an inner thread pool). See more at: AsyncTask API
I'm trying to Parse the below xml file:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel >
<title>TORi : Hosts Profiles</title>
<link>http://www.teugadio.com</link>
<description>TRi : TelOne Rdio Hots Prfiles</description>
<dc:language>en-us</dc:language>
<dc:rights>Copyright #copy; 2000-11, teluone.com, All Rights Reserved..</dc:rights>
<dc:date>2013-04-14T23:07:55+01:00</dc:date>
<dc:creator>TORi : TeluguOne Radio</dc:creator>
<dc:subject>TORi : TeluguOne Radio</dc:subject>
<item >
<title>Rajesh </title>
<link>http://www.teluradio.com/rssHstDescr.php?hostId=146</link>
<guid isPermaLink="false">http://www.telugeradio.com/rssHostDescr.php?hostId=146</guid>
<pubDate>2013-04-12</pubDate>
<description>Rajesh</description>
<media:thumbnail width='66' height='49' url='http://hostphotos/Rajh-Photo.jpg'></media:thumbnail>
</item>
<item >
<title>Prasanthi </title>
<link>http://www.tuguonadio.com/rssHostDescr.php?hostId=145</link>
<guid isPermaLink="false">http://www.telugadio.com/rsHostDescr.php?hostId=145</guid>
<pubDate>2013-04-10</pubDate>
<description>Prasanthi</description>
<media:thumbnail width='66' height='49' url='http://hostphotos/Pri-image.jpg'></media:thumbnail>
</item>
etc.......
</channel>
</rss>
I'm able to Parse the Data and my OutPut is:
TITLE TORi : Hosts Profiles
TITLE http://www.teluguoneradio.com
TITLE TORi : TeluguOne Radio Hosts Profiles
TITLE en-us
TITLE Copyright #copy; 2000-11, teluguone.com, All Rights Reserved..
TITLE 2013-04-14T23:31:24+01:00
TITLE TORi : TeluguOne Radio
TITLETORi : TeluguOne Radio
TITLE Rajesh
TITLE Prasanthi
TITLE Maireyi Ganaaju
etc..........
But ,I want to get the details with in the Item Tag itself?Could any one tell me what Should i Change in my Code?
My Required Output is:
TITLE Rajesh
TITLE Prasanthi
TITLE Maireyi Ganaaju
etc..........
Here My Code:
import static com.tort.BaseFeedParser.ITEM;
import static com.tort.BaseFeedParser.LINK;
import static com.tort.BaseFeedParser.TITLE;
import static com.tort.BaseFeedParser.PUBDATE;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HostsRssHandler extends DefaultHandler {
private List<HostsProfile> messages;
private HostsProfile currentMessage;
private StringBuilder builder;
public List<HostsProfile> getMessages(){
return messages;
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
builder.append(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null){
if (localName.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(builder.toString());
} else if (localName.equalsIgnoreCase(LINK)){
currentMessage.setLink(builder.toString());
}
else if (localName.equalsIgnoreCase(PUBDATE)){
currentMessage.setDate(builder.toString());
}
else if (localName.equalsIgnoreCase(ITEM)){
messages.add(currentMessage);
}
builder.setLength(0);
}
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
messages = new ArrayList<HostsProfile>();
builder = new StringBuilder();
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(ITEM)){
this.currentMessage = new HostsProfile();
}
if (localName.equalsIgnoreCase("thumbnail")) {
currentMessage.setMediathumbnail(attributes.getValue("url"));
}
}
}
How about adding a boolean flag insideItem?
public class HostsRssHandler extends DefaultHandler {
private boolean insideItem;
#Override
public void endElement(String uri, String localName, String name)
throws SAXException {
super.endElement(uri, localName, name);
if (this.currentMessage != null && insideItem){
if (localName.equalsIgnoreCase(TITLE)){
currentMessage.setTitle(builder.toString());
} else if (localName.equalsIgnoreCase(LINK)){
currentMessage.setLink(builder.toString());
} else if (localName.equalsIgnoreCase(PUBDATE)){
currentMessage.setDate(builder.toString());
} else if (localName.equalsIgnoreCase(ITEM)){
messages.add(currentMessage);
insideItem = false;
}
builder.setLength(0);
}
}
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(ITEM)){
this.currentMessage = new HostsProfile();
insideItem = true;
} else if (localName.equalsIgnoreCase("thumbnail") && insideItem) {
currentMessage.setMediathumbnail(attributes.getValue("url"));
}
}
}
I'm trying to make an SAX Parser for Android and started off by reading only one tag from the external XML file. I get an 'Unfortunately, -- has stopped' error. I looked at the Log file and it gives my a null reference error. My guess is the XMLAdapter class isn't working fine and I haven't been able to figure the problem out.
Here's my Main activity:
package com.vint.michiganbus;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.view.Window;
import android.util.Log;
public class listView extends Activity {
XMLGettersSetters data;
private static final String TAG = "listView";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
View layout = findViewById(R.id.layout);
TextView title[];
Log.i(TAG, "data is hello");
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://mbus.pts.umich.edu/shared/public_feed.xml"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
data = XMLHandler.data;
/**
* Makes the TextView length the size of the TextView arrays by getting the size of the
**/
title = new TextView[data.get().size()];
/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < data.get().size(); i++) {
title[i] = new TextView(this);
title[i].setText("Title = "+data.get().get(i));
((ViewGroup) layout).addView(title[i]);
}
setContentView(layout);
//setContentView(R.layout.listview);
}
}
Here's my XML Handler:
package com.vint.michiganbus;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
private static final String TAG = "In Handler";
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
Log.i(TAG, "starting Element "+localName);
if (localName.equals("livefeed"))
{
data = new XMLGettersSetters();
} else if (localName.equals("routecount")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
}
}
/**
* This will be called when the tags of the XML end.
**/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("routecount"))
data.set(elementValue);
/*else if (localName.equalsIgnoreCae("artist"))
data.setArtist(elementValue);
else if (localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
else if (localName.equalsIgnoreCase("company"))
data.setCompany(elementValue);
else if (localName.equalsIgnoreCase("price"))
data.setPrice(elementValue);
else if (localName.equalsIgnoreCase("year"))
data.setYear(elementValue);*/
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
And this is my GetterSetter class
package com.vint.michiganbus;
import java.util.ArrayList;
public class XMLGettersSetters {
private ArrayList<String> routecount = new ArrayList<String>();
public ArrayList<String> get() {
return routecount;
}
public void set(String company) {
this.routecount.add(company);
}
}
Any help will be greatly appreciated!
ps: If anyone has suggestions how to handle the XML in the URL efficiently I'd love that!
The error might be that you're trying to retrieve a web file from the activity thread. I would create an AsyncTask, put all my parser code in the doInBackground() method from AsyncTask.
Something that would look like this :
private class DownloadFilesTask extends AsyncTask<Document, Integer, Document>
{
Document doc;
String xml;
public DownloadFilesTask(){}
protected Document doInBackground(Document... params)
{
xml = xmlFunctions.getXML("Your URL");
doc = XmlFunctions.XMLfromString(xml);
return doc;
}
protected void onPostExecute(Document result)
{
//Some code changing UI from the nodes you've just parsed
}
}
then you can call this class in your onCreate using :
new DownloadTaskfiles().execute();
Hope this is of some help!
i am make a 3 file that parse "a.xml",problem is as a result i got last line not entire parsing.
so can you help me?
package barc3.barc3;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class barc3 extends Activity {
private TextView orgXmlTxt;
private TextView parsedXmlTxt;
private Button parseBtn,chartbtn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try {
setContentView(R.layout.main);
orgXmlTxt = (TextView) findViewById(R.id.orgXMLTxt);
parsedXmlTxt = (TextView) findViewById(R.id.parsedXMLTxt);
parseBtn = (Button) findViewById(R.id.parseBtn);
chartbtn =(Button) findViewById(R.id.chartbtn);
//orgXmlTxt.setText(getOriginalMyXML());
parseBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
parsedXmlTxt.setText(getParsedMyXML());
} catch (Exception e) {
// TODO Auto-generated catch block
orgXmlTxt.setText(e.getMessage());
}
}
});
chartbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(barc3.this,XMLParsingDemo.class));
}
});
} catch (Exception e) {
orgXmlTxt.setText(e.getMessage());
}
}
/**
* This method is called by OnCreate during startup to show the original XML file content
* #return
* #throws Exception
*/
private String getOriginalMyXML() throws Exception {
/* Load xml file being shown from raw resource folder */
InputStream in = this.getResources().openRawResource(R.raw.a);
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
return inLine.toString();
}
private String getParsedMyXML() throws Exception {
StringBuffer inLine = new StringBuffer();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader */
XMLHandler myExampleHandler = new XMLHandler();
xr.setContentHandler(myExampleHandler);
/* Load xml file from raw folder*/
InputStream in = this.getResources().openRawResource(R.raw.a);
/* Begin parsing */
xr.parse(new InputSource(in));
XMLDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
String s = parsedExampleDataSet.getDate();
String s2 = parsedExampleDataSet.getScore();
System.out.println("s is:::::: "+s);
System.out.println("s2 is :::::"+s2);
System.out.println(parsedExampleDataSet);
inLine.append(parsedExampleDataSet.toString());
in.close();
return inLine.toString();
}
}
package barc3.barc3;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean NewDataSet = false;
private boolean Table = false;
private boolean Date = false;
private boolean Score = false;
private XMLDataSet myParsedExampleDataSet = new XMLDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public XMLDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new XMLDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("NewDataSet")) {
this.NewDataSet = true;
}else if (localName.equals("Table")) {
this.Table = true;
}else if (localName.equals("Date")) {
this.Date = true;
}
else if (localName.equals("Score")) {
this.Score = true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("NewDataSet")) {
this.NewDataSet = false;
}else if (localName.equals("Table")) {
this.Table = false;
}else if (localName.equals("Date")) {
this.Date = false;
}
else if (localName.equals("Score")) {
this.Score = false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.Date)
{
myParsedExampleDataSet.setDate(new String(ch, start, length));
System.out.println("Date"+Date);
}
if(this.Score)
{
myParsedExampleDataSet.setScore(new String(ch, start, length));
System.out.println("Score"+Score);
}
}
}
package barc3.barc3;
public class XMLDataSet {
String Date = null;
String Score = null;
public String getDate() {
return Date;
}
public void setDate(String Date) {
this.Date = Date;
}
public String getScore() {
return Score;
}
public void setScore(String Score) {
this.Score = Score;
}
public String toString(){
return "Date is = " + this.Date
+ "\nScore is = " + this.Score;
}
}
<?xml version="1.0" encoding="utf-8" ?>
<DataSet xmlns="http://tempuri.org/">
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
- <xs:complexType>
- <xs:choice minOccurs="0" maxOccurs="unbounded">
- <xs:element name="Table">
- <xs:complexType>
- <xs:sequence>
<xs:element name="Date" type="xs:string" minOccurs="0" />
<xs:element name="Score" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
<Date>12/5/2011</Date>
<Score>5</Score>
</Table>
- <Table diffgr:id="Table2" msdata:rowOrder="1">
<Date>45/5/2011</Date>
<Score>54</Score>
</Table>
- <Table diffgr:id="Table3" msdata:rowOrder="2">
<Date>12/5/2011</Date>
<Score>12</Score>
</Table>
- <Table diffgr:id="Table4" msdata:rowOrder="3">
<Date>3/4/2011</Date>
<Score>25</Score>
</Table>
- <Table diffgr:id="Table5" msdata:rowOrder="4">
<Date>6/8/2011</Date>
<Score>45</Score>
</Table>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
The Problem is in your DefaultHandler-class:
myParsedExampleDataSet.setDate(new String(ch, start, length))
The characters-method can be called multiple times on one Tag, for example if this Tag contains entity's like > for a >.
You should use a StringBuilder in this method, so you can append all the new content to it and then get your String using the toString()-method.