how to set data in textbox after sax parsing - android

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

You'll get so many examples for this on google. I am showing you one of the. Just try this
I hope it may help you. If you've any doubt, just post it here

Related

how read xml file from website in android

I want to read file xml from website "sjc.com.vn" but it don't work. Here my source code, I don't no where wrong in this
enter code here
public class OrderXMLHandler extends DefaultHandler {
boolean currentElement = false;
String currentValue = "";
String ratelist;
String updated;
ProductInfo productInfo;
ArrayList<ProductInfo> cartList;
public String getRatelist() {
return ratelist;
}
public void setRatelist(String ratelist) {
this.ratelist = ratelist;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public ArrayList<ProductInfo> getCartList() {
return cartList;
}
public void setCartList(ArrayList<ProductInfo> cartList) {
this.cartList = cartList;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if(qName.equals("root")){
cartList = new ArrayList<ProductInfo>();
} else if(qName.equals("city"))
productInfo = new ProductInfo();
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if(localName.equalsIgnoreCase("city"))
productInfo.setName(currentValue.trim());
else if (localName.equalsIgnoreCase("buy"))
productInfo.setBuy(currentValue.trim());
else if (localName.equalsIgnoreCase("sell"))
productInfo.setSell(currentValue.trim());
else if (localName.equalsIgnoreCase("type"))
productInfo.setType(currentValue.trim());
else if (localName.equalsIgnoreCase("city"))
cartList.add(productInfo);
currentValue = "";
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Thực hiện hàm phân tích XML
parseXML();
}
//Hàm phân tích XML
private void parseXML(){
try {
URL url=new URL("http://www.sjc.com.vn/xml/tygiavang.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
OrderXMLHandler myXMLHandler = new OrderXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(url.openStream()));
TextView tv = new TextView(this);
LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
//In chi tiết sản phẩm ra giao diện ứng dụng
ArrayList<ProductInfo> cartList = myXMLHandler.getCartList();
for (ProductInfo productInfo : cartList) {
tv = new TextView(this);
tv.setText("Ten Thanh Pho: " + productInfo.getName());
ll.addView(tv);
tv = new TextView(this);
tv.setText("Buy : " + productInfo.getBuy());
ll.addView(tv);
tv = new TextView(this);
tv.setText("sell : " + productInfo.getSell());
ll.addView(tv);
tv = new TextView(this);
tv.setText("type : " + productInfo.getType());
ll.addView(tv);
tv = new TextView(this);
tv.setText("---");
ll.addView(tv);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ProductInfo {
String type="";
String sell="";
String buy="";
String name ="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSell() {
return sell;
}
public void setSell(String sell) {
this.sell = sell;
}
public String getBuy() {
return buy;
}
public void setBuy(String buy) {
this.buy = buy;
}
}

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.

How do parse xml in android using SAX Parser?

I'm a noob to android and I'm trying to learn how to parse xml with the SAX parser. I've written a test application to try to implement it, but i can't seem to make it work. I want my textview to display corresponding values from an xml but it's not working. Can anyone help?
Parser
public class ParseTestActivity extends Activity implements View.OnClickListener {
/** Called when the activity is first created. */
final static String TAG = "spotxml";
TextView tv;
WebView xml;
Button help, help2;
int livespot = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1parsed);
help = (Button) findViewById(R.id.button1);
help2 = (Button) findViewById(R.id.button2);
help.setOnClickListener(this);
help2.setOnClickListener(this);
xml = (WebView) findViewById(R.id.webView1);
try{
xml.loadUrl("http://www.xmlcharts.com/cache/precious-metals.xml");
}catch (Exception e){
e.printStackTrace();
}
try{
URL xmlcharts = new URL("http://www.xmlcharts.com/cache/precious-metals.xml");
//InputSource local = new InputSource(getResources().openRawResource(R.raw.preciousmetals));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(xmlcharts.openStream()));
//xr.parse(local);
XMLDataCollected information = doingWork.getInformation();
//String information = doingWork.getInformation();
tv.setText(information.toString());
livespot = Integer.parseInt(information.toString());
}catch(Exception e){
Toast.makeText(ParseTestActivity.this, "Error", Toast.LENGTH_LONG).show();
Log.e(TAG, "WeatherQueryError", e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
try{
URL xmlcharts = new URL("http://www.xmlcharts.com/cache/precious-metals.xml");
//InputSource local = new InputSource(getResources().openRawResource(R.raw.preciousmetals));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(xmlcharts.openStream()));
//xr.parse(local);
XMLDataCollected information = doingWork.getInformation();
//String information = doingWork.getInformation();
tv.setText(information.toString());
livespot = Integer.parseInt(information.toString());
}catch(Exception e){
Toast.makeText(ParseTestActivity.this, "Error", Toast.LENGTH_LONG).show();
Log.e(TAG, "WeatherQueryError", e);
}
break;
case R.id.button2:
try{
//URL xmlcharts = new URL("http://www.xmlcharts.com/cache/precious-metals.xml");
InputSource local = new InputSource(getResources().openRawResource(R.raw.preciousmetals));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
//xr.parse(new InputSource(xmlcharts.openStream()));
xr.parse(local);
XMLDataCollected information = doingWork.getInformation();
//String information = doingWork.getInformation();
tv.setText(information.toString());
livespot = Integer.parseInt(information.toString());
}catch(Exception e){
Toast.makeText(ParseTestActivity.this, "Error", Toast.LENGTH_LONG).show();
Log.e(TAG, "WeatherQueryError", e);
}
break;
}
}}
Content Handler
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HandlingXMLStuff extends DefaultHandler {
private boolean in_prices = false;
private boolean in_pricelist = false;
private boolean in_uspricegold = false;
private boolean in_uspricesilver = false;
String gs = null;
String ss = null;
private XMLDataCollected info = new XMLDataCollected();
//public String getInformation(){
// return info.datatoString();
//}
public XMLDataCollected getInformation(){
return this.info;
}
#Override
public void startDocument() throws SAXException {
this.info = new XMLDataCollected();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("prices")) {
this.in_prices = true ;
}else if (localName.equalsIgnoreCase("pricelist")) {
String attrValue = attributes.getValue("currency");
if (attrValue.equalsIgnoreCase("usd")){
this.in_pricelist = true;
}else if (localName.equalsIgnoreCase("price")){
String attrValue2 = attributes.getValue("commodity");
if (attrValue2.equalsIgnoreCase("gold")){
this.in_uspricegold = true;
}else if (localName.equalsIgnoreCase("price")){
String attrValue3 = attributes.getValue("commodity");
if (attrValue3.equalsIgnoreCase("silver")){
this.in_uspricesilver = true;
}
}}}
}
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("prices")) {
this.in_prices = false;
}else if (localName.equalsIgnoreCase("pricelist")) {
this.in_pricelist = false;
}else if (localName.equalsIgnoreCase("price")) {
this.in_uspricegold = false;
}else if (localName.equalsIgnoreCase("price")) {
this.in_uspricesilver = false;
}
}
#Override
public void characters(char[] ch, int start, int length)throws SAXException {
if(this.in_uspricegold) {
//info.setSpotGold(new String (ch, start, length));
//}
int spotgold = Integer.parseInt(new String (ch, start, length));
info.setSpotGold(spotgold);
this.in_uspricegold = false;
}else{}
if(this.in_uspricesilver){
//info.setSpotSilver(new String(ch, start, length));
// }
int spotsilver = Integer.parseInt(new String(ch, start, length));
info.setSpotSilver(spotsilver);
this.in_uspricesilver = false;
}else{}
}
}
Collected Data Set
public class XMLDataCollected{
private int spotsilver = 0;
private int spotgold = 0;
public int getSpotGold() {
return spotgold;
}
public void setSpotGold(int spotgold){
this.spotgold = spotgold;
}
public int getSpotSilver() {
return spotsilver;
}
public void setSpotSilver(int spotsilver){
this.spotsilver = spotsilver;
}
public String toString(){
return "gold " + spotgold + " silver "+ spotsilver;
}
}
First of all your method characters has to be much simpler. The only thing that it does is to read the characters between the tags. It will be like this:
public void characters(char[] ch, int start, int end) {
buffer.append(new String(ch, start, end));
}
As you can see I'm using a StringBuffer as a private field. It's instantiate at the beginning of the startElement method and "resetted" at the beginning of the endElement.
value = buffer.toString();
buffer.setLength(0);
The field value will actually keep the real value of the field.
All my class for reference:
private String value;
private StringBuffer buffer;
#Override
public void startElement(
String nameSpaceURI,
String localName,
String qName,
Attributes atts
) {
buffer = new StringBuffer();
if(localName.equals("myTag"))
bean = new Bean();
}
public void endElement(
String uri,
String localName,
String qName) {
value = buffer.toString();
buffer.setLength(0);
if(localName.equals("myTag") {
bean.setSomething(value);
}
}
public void characters(char[] ch, int start, int end) {
buffer.append(new String(ch, start, end));
}
Hope this helps. :)
EDIT
Here the code adapted to the op xml. I haven't tried it but SHOULD work. ;)
private String value;
private StringBuffer buffer;
private XMLCOllected info;
private boolean inPriceList;
private boolean inGold;
private boolean inSilver;
#Override
public void startElement(
String nameSpaceURI,
String localName,
String qName,
Attributes atts
) {
buffer = new StringBuffer();
if(localName.equals("prices")) {
this.info = new XMLCollected();
} else if(localName.equals("pricelist")) {
String attr = atts.getValue("currency");
if(attr.equals("usd")) {
this.inPriceList = true;
}
} else if(localName.equals("price") && inPrices) {
String attr = atts.getValue("commodity");
if(attr.equals("gold")) {
this.inGold = true;
} else if(attr.equals("silver")) {
this.inSilver = true;
}
}
}
public void endElement(
String uri,
String localName,
String qName) {
value = buffer.toString();
buffer.setLength(0);
if(localName.equals("price") && inGold && inPriceList) {
this.info.setSpotGold(value);
this.inGold = false;
} else if(localName.equals("price") && inSilver && inPriceList) {
this.info.setSpotSilver(value);
this.inSilver = false;
} else if(localName.equals("pricelist")) {
this.inPriceList = false;
}
}
public void characters(char[] ch, int start, int end) {
buffer.append(new String(ch, start, end));
}

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