SAX parsing produces a null pointer exception - android

I retrieve XML from a server, save it into an SD card, then parse that XML. I get this exception:
03-19 13:53:26.943: E/AndroidRuntime(12512): FATAL EXCEPTION: main
03-19 13:53:26.943: E/AndroidRuntime(12512): java.lang.NullPointerException.
I am using this code:
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadFromUrl("http://www.androidpeople.com/wp- content/uploads/2010/06/example.xml","example.xml");
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
String path = Environment.getExternalStorageDirectory() +"../xmls"+"/example.xml";
File file = new File(path);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
DataHandler myXMLHandler = new DataHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));//parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from DataHandler SitlesList Object */
sitesList = DataHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getWebsite().size()];
category = new TextView[sitesList.getCategory().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
private void DownloadFromUrl(String DownloadUrl, String fileName)
{
URL url;
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
try {
url = new URL(DownloadUrl);
File file = new File(dir, fileName);
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
//Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //you can write here any link
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And my handler class is :
Boolean currentElement = false;
Context theContext;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList()
{
return sitesList;
}
public static void setSitesList(SitesList sitesList)
{
DataHandler.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
super.startElement(uri, localName, qName, attributes);
currentElement = true;
if (localName.equals("maintag"))
{
/** Start */
sitesList = new SitesList();
}
else if (localName.equals("website"))
{
/** Get attribute value */
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
else if (localName.equalsIgnoreCase("website"))
sitesList.setWebsite(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if (currentElement)
{
currentValue = new String(ch, start, length);
currentElement = false;
}
}
And my list class is:
/** Variables */
private ArrayList name = new ArrayList();
private ArrayList website = new ArrayList();
private ArrayList category = new ArrayList();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
public ArrayList getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList getCategory() {
return category;
}
public void setCategory(String category) {
this.category.add(category);
}
The XML file is downloaded and saved into the SD card properly but not parsed.

SAX (Simple API for XML) is an event-based sequential access parser API developed by the XML-DEV mailing list for XML documents. SAX provides a mechanism for reading data from an XML document that is an alternative to that provided by the Document Object Model (DOM). Where the DOM operates on the document as a whole, SAX parsers operate on each piece of the XML document sequentially
Please refer this link for your solution.
It will help you.

Related

Null Pointer Exception in Android Xml Parsing

I'm developing an Xml parsing application. The URL is not trusted when it is opened from the browser. There is no way to correct it from server side. So I used "trsut anybody" code.
But still I'm getting a null pointer exception.
Please help me with this.
Thanx in advance
this is my code.
public class SitesList {
/** Variables */
private ArrayList<String> From_Currency = new ArrayList<String>();
private ArrayList<String> To_Currency = new ArrayList<String>();
private ArrayList<String> exrt_buy = new ArrayList<String>();
private ArrayList<String> exrt_sell = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getFrom_Currency() {
return From_Currency;
}
public void setFrom_Currency(String From_Currency) {
this.From_Currency.add(From_Currency);
}
public ArrayList<String> getTo_Currency() {
return To_Currency;
}
public void setTo_Currency(String To_Currency) {
this.To_Currency.add(To_Currency);
}
public ArrayList<String> getexrt_buy() {
return exrt_buy;
}
public void setexrt_buy(String exrt_buy) {
this.exrt_buy.add(exrt_buy);
}
public ArrayList<String> getexrt_sell() {
return exrt_sell;
}
public void setexrt_sell(String exrt_sell) {
this.exrt_sell.add(exrt_sell);
}
}
MyXMLHandler class
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("DOC"))
{
sitesList = new SitesList();
}
/*} else if (localName.equals("website")) {
String attr = attributes.getValue("category");
sitesList.setCategory(attr);
}*/
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equalsIgnoreCase("From_Currency"))
sitesList.setFrom_Currency(currentValue);
else if (localName.equalsIgnoreCase("To_Currency"))
sitesList.setTo_Currency(currentValue);
else if (localName.equalsIgnoreCase("exrt_buy"))
sitesList.setexrt_buy(currentValue);
else if (localName.equalsIgnoreCase("exrt_sell"))
sitesList.setexrt_sell(currentValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
XMLParsingExample class
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
URL url;
HttpsURLConnection https;
HttpURLConnection conn = null;
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
url = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
try {
https = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
} else {
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView From_Currency[];
TextView To_Currency[];
TextView exrt_buy[];
TextView exrt_sell[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("https://222.165.187.91/ex_rate/XML_LOLC_EXRT.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
From_Currency = new TextView[sitesList.getFrom_Currency().size()];
To_Currency = new TextView[sitesList.getTo_Currency().size()];
exrt_buy = new TextView[sitesList.getexrt_buy().size()];
exrt_sell = new TextView[sitesList.getexrt_sell().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getFrom_Currency().size(); i++) {
From_Currency[i] = new TextView(this);
From_Currency[i].setText("Name = "+sitesList.getFrom_Currency().get(i));
To_Currency[i] = new TextView(this);
To_Currency[i].setText("Website = "+sitesList.getTo_Currency().get(i));
exrt_buy[i] = new TextView(this);
exrt_buy[i].setText("Website Category = "+sitesList.getexrt_buy().get(i));
exrt_sell[i] = new TextView(this);
exrt_sell[i].setText("Website Category = "+sitesList.getexrt_sell().get(i));
layout.addView(From_Currency[i]);
layout.addView(To_Currency[i]);
layout.addView(exrt_buy[i]);
layout.addView(exrt_sell[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
private void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}

issues in SAX parser data not loaded in specific tag

hello friends i have one spinner adapter which contain data from web service and i fill on it as follow
Main.Java
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.findyourfate.com/rss/yearly-horoscope.asp?sign=Leo"); // URL of the XML
System.out.println("URL Y "+url);
/**
* 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;
mTextViewDate.setText("Date : "+ data.getTitle());
mTextViewDesc.setText(data.getDescription());
System.out.println("data.getDescription() "+data.getDescription());
**XMLGettersSetters.java **
public class XMLGettersSetters {
String title="";
String description="" ;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
XMLHandler.java
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("channel"))
{
data = new XMLGettersSetters();
} else if (localName.equals("item")) {
/**
* 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("title"))
data.setTitle(elementValue);
else if (localName.equalsIgnoreCase("description"))
data.setDescription(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;
}
}
}
when i run above code it give description only GENERAL . other text is not getting so any idea how can i solve it ?
#Override
public String toString() {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
sb.append(title);
sb.append('\n');
sb.append(pubdate);
sb.append(link);
sb.append('\n');
sb.append(description);
sb.append('\n');
return sb.toString().toignorecase();
}
try to add this Line in your **XMLGettersSetters.java **

Getting xml data and to store in the form of array list

Iam getting the data but i want to group some particular data in the form of a group such as in airport list namely
JFK in that all lat,long,name,code of the airport has to make one array similarly the other airports.Please help me the issue.
main java class:
public String getAirportListHTTPURL(String mAirportLocation,Double airportLatitude, Double airportLongitude, String mAirlineCode, boolean mAirport2, String mAddress2, String mCity2, String mState2, String mCountry2) {
String url = CarmelURLConstants.LIVE_URL.toString();
URL u = new URL(url);
URLConnection uc = u.openConnection();
HttpURLConnection http = (HttpURLConnection) uc;
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-type", "text/xml; charset=utf-8");
String xmldata = Here i used the xml format Syntax data
System.out.println(xmldata);
OutputStream out = http.getOutputStream();
Writer wout = new OutputStreamWriter(out);
wout.write(xmldata);
wout.flush();
wout.close();
// Reading Data from the server using getInputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(http.getInputStream()));
System.out.println("code..."+http.getResponseCode());
String result, responsedata = " ";
RequestName = "AirportlistByPickUpAddress Request:-";
ResponseName = "AirportlistByPickupAddress Response:-";
while ((result=rd.readLine()) != null) {
System.out.println(result");
responsedata = result;
// Method to parse in SAX Parser
mParsedValue = ParseAirportLocationResponse(result);
}
// updateTraceFile(xmldata, responsedata,RequestName,ResponseName);
}catch(Exception e){
mParsedValue = e.getMessage();
e.printStackTrace();
}
return mParsedValue;
}
private String ParseAirportLocationResponse(String result) {
try {
// Create a XMLReader from SAXParser
XMLReader mXmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
AirportHandler Airportlist = new AirportHandler();
// Apply Handler to XML Reader
mXmlReader.setContentHandler(Airportlist);
// Start the Process to Parse
InputSource is = new InputSource(new StringReader(result));
mXmlReader.parse(is);
} catch (Exception e) {
System.out.println(e);
}
return result;// Get the Parsed Data
}
In the XMLSETTERS CLASS:
public class XMLGettersSetters {
public static ArrayList<String> airportCode = new ArrayList<String>();
public static ArrayList<String> airportName = new ArrayList<String>();
public static ArrayList<String> latitude = new ArrayList<String>();
public static ArrayList<String> longitude = new ArrayList<String>();
public ArrayList<String> getlongitude() {
return longitude;
}
public void setlongitude(String longitude) {
this.longitude.add(longitude);
Log.i("This is the longitude:", longitude);
}
public ArrayList<String> getairportCode() {
return airportCode;
}
public void setairportCode(String airportCode) {
this.airportCode.add(airportCode);
Log.i("This is the airportCode:", airportCode);
}
public ArrayList<String> getairportName() {
return airportName;
}
public void setairportName(String airportName) {
this.airportName.add(airportName);
Log.i("This is the airportName:", airportName);
}
public ArrayList<String> getlatitude() {
return latitude;
}
public void setlatitude(String latitude) {
this.latitude.add(latitude);
Log.i("This is the latitude:", latitude);
}
}
In the Airport handler class:
public class AirportHandler 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) {
AirportHandler.data = data;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("getAirportListByPickUpAddressResponse"))
{
data = new XMLGettersSetters();
}
else if (localName.equals("airportList")) {
}
}
/**
* 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("airportCode"))
data.setairportCode(elementValue);
else if (localName.equalsIgnoreCase("airportName"))
data.setairportName(elementValue);
else if (localName.equalsIgnoreCase("latitude"))
data.setlatitude(elementValue);
else if (localName.equalsIgnoreCase("longitude"))
data.setlongitude(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;
}
}
}
After performing XML parsing try like this
ArrayList<String> aList = new ArrayList<String>();
aList.add("your string");

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.

Error parsing xml using SAXParser

I have a problem when parsing xml from the internet. The parser doesn't return all the data correctly.
Three are three errors:
correct result -->return result
161:1:161-->1:1:161
330:2:132-->3:2:132
421:2:223-->4:2:223
Copy of the xml file I am trying to parse
https://docs.google.com/open?id=0BwXEx9yI14inT1BnR2xzYnJEX0E
Activity
public class DataBaseUpdateService_1 extends Activity {
private TextView TextView1 ;
private LinearLayout linearlayout1 ;
private TextView title[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_item);
linearlayout1 = (LinearLayout)findViewById(R.id.linearlayout1);
TextView1 = (TextView)findViewById(R.id.textView1);
MyDBHelper dbHelper =new MyDBHelper(DataBaseUpdateService_1.this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://123.com/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
DataBaseUpdate_XMLHandler XMLHandler = new DataBaseUpdate_XMLHandler();
xr.setContentHandler(XMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
}catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
int itemCount = DataBaseUpdate_XMLHandler.array.size();
db.delete("hymns_match", null, null);
try{
for(int i=0;i<itemCount;i++) {
String songs_id=DataBaseUpdate_XMLHandler.array.get(i).get("songs_id");
String songs_book_id=DataBaseUpdate_XMLHandler.array.get(i).get("songs_book_id");
String songs_book_ch=DataBaseUpdate_XMLHandler.array.get(i).get("songs_book_ch");
TextView tv = new TextView(DataBaseUpdateService_1.this);
tv.setText(songs_id + ":"+songs_book_id+ ":"+songs_book_ch);
linearlayout1.addView(tv);
}
}catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
DataBaseUpdate_XMLHandler
public class DataBaseUpdate_XMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue=null;
static ArrayList<LinkedHashMap<String, String>> array;
LinkedHashMap map;
#Override
public void startDocument() throws SAXException {
array = new ArrayList<LinkedHashMap<String, String>>();
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("song")) {
map = new LinkedHashMap<String, Object>();
currentValue=null;
}
/*Get attribute
* else if (localName.equals("website")) {
* String attr = attributes.getValue("category");
* sitesList.setCategory(attr);}
* */
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("songs_id")){
map.put("songs_id",currentValue);}
else if (localName.equalsIgnoreCase("songs_book_id")){
map.put("songs_book_id", currentValue);}
else if (localName.equalsIgnoreCase("songs_book_ch")){
map.put("songs_book_ch", currentValue);}
else if (localName.equalsIgnoreCase("song")){
array.add(map);}
}
/** Called to get tag characters
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
Can you give some advice about what's wrong here?
According to the SAX definition characters() method can be called multiple times per elements. So it should accumulate the text; if this is happening then your code will not work.

Categories

Resources