how to do nested parsing using SAX Parser in android - android

I have a xml like this :
<channel>
<item>
<link>http://uopnews.unipune.ac.in/Lists/Calendar/DispForm.aspx?ID=14</link>
<description><![CDATA[<div><b>Location:</b> PUMBA Auditorium - University of Pune</div> <div><b>Start Time:</b> 5/15/2012 11:00 AM</div>
<div><b>End Time:</b> 5/15/2012 2:00 PM</div>
<div><b>Description:</b> <div>General B. C. Joshi Memorial Lecture 2012- Perspective on War in the 21st Century - By Lt. Gen. A. K. Singh</div></div>
<div><b>Attachments:</b> http://uopnews.unipune.ac.in/Lists/Calendar/Attachments/14/bcjoshi2012[1].pdf<br></div>
]]></description>
</item>
</channel>
I can parse upto description tag using SAX Parser here is my SAXhandler class.
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.R.string;
import android.util.Log;
public class XMLParsingHandler extends DefaultHandler {
private static final String NEW_DATA_SET = "image";
private String currentValue = "";
private String currentTag = "";
private HashMap<String, Object> root;
private HashMap<String, String> child;
private String[] tagArray = null;
private ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
private String describe;
public XMLParsingHandler(String[] tagArray) {
this.tagArray = tagArray;
}
public void parseContent(String urlStr) {
try {
URL url = new URL(urlStr);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
xmlReader.parse(new InputSource(url.openStream()));
Log.d("PRASER", "Afer parsering done" + arraylist);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void startDocument() throws SAXException {
super.startDocument();
root = new HashMap<String, Object>();
System.out.println("root=" + root);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
Log.d("tag", "StartElement started here");
currentTag = localName;
Log.d("start", "in start doc current atg---------: " + currentTag);
if (localName.equals(NEW_DATA_SET)) {
child = new HashMap<String, String>();
currentValue = new String();
}
describe=new String();
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
currentValue = new String(ch, start, length);
Log.d("other", "in CHARACTER : CurrentValue=---------" + currentValue
+ " currentTag-------" + currentTag);
if(currentTag.equals("description") ) {
String str= new String(ch, start, length);
//describe=new String();
describe=describe+""+currentValue;
Log.d("describe", "in CHARACTER : describe=---------" + describe);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
Log.d("end", "currentTag:"+currentTag+"------currentValue"+currentValue);
if(child!=null)
{
for (int i = 0; i < tagArray.length; i++) {
if (currentTag.equals("description")){
child.put(currentTag, currentValue);
}
if (currentTag.equals(tagArray[i]))
{
child.put(currentTag, currentValue);
Log.d("tagarray","currentTag="+ currentTag+"currentValue:"+currentValue);
currentValue=null;
currentValue=new String();
currentTag=null;
currentTag=new String();
}
}
if (localName.equals(tagArray[tagArray.length - 1])) {
arraylist.add(child);
child=null;
child=new HashMap<String, String>();
}
}
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
Log.d("tag", "in end doc");
}
public ArrayList<HashMap<String, String>> getArraylist() {
return arraylist;
}
public void setArraylist(ArrayList<HashMap<String, String>> arraylist) {
this.arraylist = arraylist;
}
#Override
public String toString() {
return arraylist.toString();
}
}
and I am Calling it like this :
userMap = new HashMap<String, String>();
XMLParsingHandler x = new XMLParsingHandler(tagArray);
x.parseContent(url);
System.out.println("Element FOund");
userMap = x.getArraylist().get(0);
System.out.println("Map " + userMap);
here my userMap only print valu upto description tag after it only shows null value. i need all data from description. Is there any way?

Find the below sax parser code
public class IndianNewsHandler implements ContentHandler {
private String value = "";
private Item item = null;
private TextView tvRef = null;
private Activity myActivity = null;
private static IndianNewsHandler mIndianNewsHandler;
public static IndianNewsHandler getInstance() {
if (mIndianNewsHandler == null) {
mIndianNewsHandler = new IndianNewsHandler();
}
return mIndianNewsHandler;
}
private IndianNewsHandler() {
}
private ArrayList<Item> content = new ArrayList<Item>();
// private ArrayList<String> myList = new ArrayList<String>();
private boolean STATUS_PARSE = true;
private boolean ITEM_STATUS = false;
public ArrayList<Item> getData() {
return content;
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (STATUS_PARSE) {
this.value = localName;
if (localName.equals("item")) {
item = new Item();
ITEM_STATUS = true;
}
}
}
public void characters(char[] text, int start, int length)
throws SAXException {
if (STATUS_PARSE && ITEM_STATUS) {
StringBuffer buffer = new StringBuffer();
buffer.append(text, 0, length);
if (buffer != null) {
if (this.value.equals("title")) {
System.out.println("I am in title"
+ buffer.toString().trim());
if (buffer.toString().trim().length() > 1)
item.setTitle(buffer.toString().trim());
} else if (value.equals("description"))
{
String url = buffer.toString().trim();
try {
if (url.contains("img src=")) {
final String url_string = url.split("img src=")[1]
.split(">")[0].replace("'", "");
System.out.println("FInal URL :" + url_string);
if (url_string != null) {
//here i am creating async task for convert image
new CovertingImageToByte(url_string).execute();
if (buffer.toString().trim().length() > 1) {
String des = buffer.toString().split(">")[1];
item.setDes(des);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
class CovertingImageToByte extends AsyncTask<String,Integer, String>{
String imageUrl;
public CovertingImageToByte(String urlString) {
this.imageUrl=urlString;
}
#Override
protected String doInBackground(String... params) {
try {
InputStream is = new URL(imageUrl)
.openStream();
Bitmap bitmap = BitmapFactory
.decodeStream(is);
byte[] mybyt = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG,
0, stream);
mybyt = stream.toByteArray();
System.out.println("test"
+ mybyt.length);
item.setImg(mybyt);
// System.out.println("Finallly List123 size ::::::::::"+content.get(0).getImg().length);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (STATUS_PARSE) {
if (localName.equals("item")) {
content.add(item);
}
if (content.size() >= 15) {
STATUS_PARSE = false;
}
}
}
#Override
// do nothing methods
public void setDocumentLocator(Locator locator) {
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
System.out.println("Finallly List size ::::::::::" + content.get(1));
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {
}
public void skippedEntity(String name) throws SAXException {
}
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException {
}
public void processingInstruction(String target, String data)
throws SAXException {
}
}

Related

Android: not shows all text of XML from URL

I am creating the recovery of text using XML from a URL. I get the text. But I have a problem.
When the text of an item of the XML is large, in the TextView not shows all text of the XML.
What can be the error?
ACTIVITY
class tareaAsyncHorariosTarifas extends AsyncTask<Void, Void, Void> {
XmlReader helper;
#Override
protected Void doInBackground(Void... params) {
helper = new XmlReader(color);
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getHorarios());
}
if(builder.toString().equals("")) {
horario2.setText("-");
} else {
horario2.setText(Html.fromHtml(builder.toString()));
}
builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getTarifas());
}
if(builder.toString().equals("")) {
tarifa2.setText("-");
} else {
tarifa2.setText(Html.fromHtml(builder.toString()));
}
}
}
XML READER
public XmlReader(String color) {
this.color = color;
}
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(URL + color + ".xml").openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) {
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currTag = true;
currTagVal = "";
if (localName.equals("color")) {
post = new HorariosTarifasObj();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("horarios")) {
post.setHorarios(currTagVal);
} else if(localName.equalsIgnoreCase("tarifas")) {
post.setTarifas(currTagVal);
} else if (localName.equalsIgnoreCase("color")) {
posts.add(post);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}

Android: is possible to Improve my code to download XML from URL?

In internet I got a code to download the text of an XML from a URL. The works ok. My problem is that I have to download many XML simultaneously.
I can to improve my code to make downloading faster? thanks
XMLParser
public XmlReader(String monumento) {
this.monumento = monumento;
}
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(URL + monumento + ".xml").openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) {
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currTag = true;
currTagVal = "";
if (localName.equals("monumento")) {
post = new HorariosTarifasObj();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("horarios")) {
post.setHorarios(currTagVal);
} else if(localName.equalsIgnoreCase("tarifas")) {
post.setTarifas(currTagVal);
} else if (localName.equalsIgnoreCase("monumento")) {
posts.add(post);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
ACTIVITY.java
class tareaAsyncHorariosTarifas extends AsyncTask<Void, Void, Void> {
XmlReader helper;
#Override
protected Void doInBackground(Void... params) {
helper = new XmlReader(monumento);
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getHorarios());
}
if(builder.toString().equals("")) {
horario2.setText("-");
} else {
horario2.setText(Html.fromHtml(builder.toString()));
}
builder = new StringBuilder();
for (HorariosTarifasObj post : helper.posts) {
builder.append(post.getTarifas());
}
if(builder.toString().equals("")) {
tarifa2.setText("-");
} else {
tarifa2.setText(Html.fromHtml(builder.toString()));
}
}
}

XML Parser returns last item, not the rest

my XML Content: (FileName: sku.xml)
<skus>
<id>p1</id>
<id>test</id>
<id>aa</id>
<id>bb</id>
<id>cc</id>
<id>dd</id>
<id>ee</id>
<id>ff</id>
<id>gg</id>
<id>hh</id>
<id>ii</id>
<id>jj</id>
<id>kk</id>
<id>ll</id>
</skus>
my SAX XML PARSER Class:
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
List<XMLSetAdd> setAdds = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// get the News list`
setAdds = saxHandler.getIds();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return News list
return setAdds;
}
}
My SAX XML HANDLER:
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equals("skus")) {
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("skus")) {
setAdds.add(setAdd);
} else if (qName.equals("id")) {
setAdd.setId(tempVal);
}
}
}
my XML SetAdd:
public class XMLSetAdd {
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
private String Id;
}
My Async Class:
private class GetXMLTask extends AsyncTask<String, Void, List<XMLSetAdd>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(List<XMLSetAdd> news) {
try
{
for (int i = 0; i < IdsL.size(); i++)
{
skusList.add(IdsL.get(i).getId());
Log.d("XML content",IdsL.get(i).getId());
}
skusQuery = new Bundle();
skusQuery.putStringArrayList("ITEM_ID_LIST", skusList);
GetAllSkusAsync runner = new GetAllSkusAsync();//Some Async to run after
runner.execute();
}
catch (Exception ex)
{
Log.d("Error Reading XML: ", ex.toString());
Toast.makeText(
getApplicationContext(),"Connection Error!"
Toast.LENGTH_SHORT).show();
}
}
/*
* uses HttpURLConnection to make Http request from Android to download
* the XML file
*/
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
Log.d("Error in asyncTask XML: ", ex.toString());
ex.printStackTrace();
}
return output.toString();
}
private List<XMLSetAdd> IdsL;
#Override
protected List<XMLSetAdd> doInBackground(String... urls) {
IdsL = null;
List<XMLSetAdd> myList = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
IdsL = SAXXMLParser.parse(stream);
myList = SAXXMLParser.parse(stream);
}
// stream.close();
return IdsL;
}
}
The code which I use to call Async Class:
String URL = "http://someaddress/php/sku.xml";
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
Now When I run this code and Log the result ,my list returns the last xml child which based on my xml file is "ll" and the rest of xml is not added to the file.
The list should return all of the ids but returns the last one.
Check following code. Edited SAX XML HANDLER.
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equals("skus")) {
setAdds = new List<XMLSetAdd>();
}else if(qName.equals("id")){
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("skus")) {
} else if (qName.equals("id")) {
setAdd.setId(tempVal);
setAdds.add(setAdd);
}
}
}
The reason is because you are only adding items to the list when endElement is skus. You should be adding one element for each id as follows:
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("skus")) {
// setAdds.add(setAdd); // dont add here..
} else if (qName.equals("id")) {
setAdd.setId(tempVal); // if ending with id
setAdds.add(setAdd); // then add id to the list
}
}
Update
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equals("id")) {
setAdd = new XMLSetAdd(); // new item for each id
}
}
#Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
curentElement=localName;
if(qName.equals("skus")){
setAdd = new XMLSetAdd();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
String value = new String(ch, start, length);
if(curentElement.equals("id")){
tempVal=value;
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
curentElement = "";
if (localName.equals("id")) {
setAdd.setId(tempVal);
}else if(localName="skus"){
setAdds.add(setAdd);
}
Try this way
Update your parse
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
// Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// reset
if (qName.equals("id")) {
tempVal = "";
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("id")) {
setAdd.setId(tempVal);
setAdds.add(setAdd);
}
}

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

Parse XML on Android

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

Categories

Resources