Parsing XML from the Net - Using the SAXParser

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Progress!

Postby mmgill » Fri Apr 09, 2010 1:07 am

hi guys,

I have gotten a little further on the project. It now gathers the input of the user, constructs the url, get the info and parses it, and displays the titles in a textview. Im just having trouble putting the titles in a listview so that once the user clicks a place it will display a map with the lat/long from that location.

Anyone know how i can get the items in a listview or if you can use a clicklistener on each different item in the textview? what would be easier.

Thanks,

Mg
Attachments
NewProg.zip
here's what i have so far. just need a way to select an individual item
(32.62 KiB) Downloaded 145 times
mmgill
Junior Developer
Junior Developer
 
Posts: 20
Joined: Thu Mar 04, 2010 8:40 pm

Top

Re: Progress!

Postby songotho » Fri Apr 09, 2010 4:06 am

mmgill wrote:hi guys,

I have gotten a little further on the project. It now gathers the input of the user, constructs the url, get the info and parses it, and displays the titles in a textview. Im just having trouble putting the titles in a listview so that once the user clicks a place it will display a map with the lat/long from that location.

Anyone know how i can get the items in a listview or if you can use a clicklistener on each different item in the textview? what would be easier.

Thanks,

Mg


Hi men,

I think that it is not difficult to list whatever U want in listview if U have one array. U can follow some sample in here

Hope help u.

Alex.
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Postby itsricardo881 » Mon Apr 12, 2010 10:52 am

thanks alot for the article

You are a god!!
itsricardo881
Freshman
Freshman
 
Posts: 2
Joined: Mon Feb 15, 2010 3:02 pm

FINALLY!!

Postby mmgill » Tue Apr 13, 2010 3:45 pm

Hi everyone,

Just got a huge portion of the Local Search application working. Right now it is hard coded for my location (lat/long) but there is code in there that should populate the edittext on create. Could someone look at those and make sure it could work on a real phone? From there it takes the users input (food, bars, banks, etc) and brings up a list of businesses near that location. We just need to find a way to plot the lat/long of a specific business when it is clicked on a mapview. Any suggestions or comments will really help me improve this project. Thanks again for all the help so far!

Mg
Attachments
NewProg.zip
Uptodate but messy code
(44.99 KiB) Downloaded 135 times
mmgill
Junior Developer
Junior Developer
 
Posts: 20
Joined: Thu Mar 04, 2010 8:40 pm

Postby pabmadi » Wed Apr 14, 2010 3:16 pm

I'm parsing this XML : http://www.google.com/ig/api?weather=Madrid,Spain without any problem; BUT with this : http://www.mercadolibre.com.ar/jm/searchXml?as_categ_id=1000&as_filtro_id=24_HS I get this error in the LogCat: "WARN/Pablo-ERR(1643): org.apache.harmony.xml.ExpatParser$ParseException: At line 4, column 21: not well-formed (invalid token)"

Whats wrong with this XML, and how can I solve it??

Thanks.-
pabmadi
Junior Developer
Junior Developer
 
Posts: 19
Joined: Thu Apr 08, 2010 9:25 pm

ExtractedString being set to empty

Postby actionmouse » Sun Apr 18, 2010 11:04 pm

Hi,
I'm trying to run this code but the end result shows:
ExtractedString =

The int works fine.

Im doing some logging and I see that somehow setExtractedString() gets called twice. The second time around the value is empty so its setting the var to empty, that's why it's displaying that way, but why is this passing twice:

if(this.in_mytag) ??

Thanks for any help.
actionmouse
Freshman
Freshman
 
Posts: 3
Joined: Sun Apr 18, 2010 10:59 pm

Top

Re: ExtractedString being set to empty

Postby actionmouse » Mon Apr 19, 2010 1:22 am

actionmouse wrote:Hi,
I'm trying to run this code but the end result shows:
ExtractedString =

The int works fine.

Im doing some logging and I see that somehow setExtractedString() gets called twice. The second time around the value is empty so its setting the var to empty, that's why it's displaying that way, but why is this passing twice:

if(this.in_mytag) ??

Thanks for any help.


I made a new XML file on my server and that one seemed to work. I killed all of the white space in my own example.xml and that fixed it. Any way to remove white space in java to eliminate this issue?

Thanks
actionmouse
Freshman
Freshman
 
Posts: 3
Joined: Sun Apr 18, 2010 10:59 pm

Postby Arawass » Tue Apr 20, 2010 4:56 pm

would it include images in the parsing or not?

as i'm struggling to do this.
Arawass
Freshman
Freshman
 
Posts: 3
Joined: Mon Apr 12, 2010 1:14 am

Postby Arawass » Tue Apr 27, 2010 5:07 pm

I've tried this tutorial to parse some info out of this RSS feed but i don't get anything in return.
This is what i've modified only
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.parsingxml;
  2.  
  3. import org.xml.sax.Attributes;
  4. import org.xml.sax.SAXException;
  5. import org.xml.sax.helpers.DefaultHandler;
  6.  
  7.  
  8. public class ExampleHandler extends DefaultHandler{
  9.  
  10.      // ===========================================================
  11.      // Fields
  12.      // ===========================================================
  13.      
  14.      private boolean in_outertag = false;
  15.      private boolean in_innertag = false;
  16.      private boolean in_mytag = false;
  17.      private boolean in_url = false;
  18.      
  19.      private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
  20.  
  21.      // ===========================================================
  22.      // Getter & Setter
  23.      // ===========================================================
  24.  
  25.      public ParsedExampleDataSet getParsedData() {
  26.           return this.myParsedExampleDataSet;
  27.      }
  28.  
  29.      // ===========================================================
  30.      // Methods
  31.      // ===========================================================
  32.      @Override
  33.      public void startDocument() throws SAXException {
  34.           this.myParsedExampleDataSet = new ParsedExampleDataSet();
  35.      }
  36.  
  37.      @Override
  38.      public void endDocument() throws SAXException {
  39.           // Nothing to do
  40.      }
  41.  
  42.      /** Gets be called on opening tags like:
  43.       * <tag>
  44.       * Can provide attribute(s), when xml was like:
  45.       * <tag attribute="attributeValue">*/
  46.      @Override
  47.      public void startElement(String namespaceURI, String localName,
  48.                String qName, Attributes atts) throws SAXException {
  49.           if (localName.equals("channel")) {
  50.                this.in_outertag = true;
  51.           }else if (localName.equals("item")) {
  52.                this.in_innertag = true;
  53.           }else if (localName.equals("title")) {
  54.                this.in_mytag = true;
  55.           }else if (localName.equals("url")) {
  56.               this.in_url = true;
  57.           }
  58. //          }else if (localName.equals("tagwithnumber")) {
  59. //               // Extract an Attribute
  60. //               String attrValue = atts.getValue("thenumber");
  61. //               int i = Integer.parseInt(attrValue);
  62. //               myParsedExampleDataSet.setExtractedInt(i);
  63. //          }
  64.      }
  65.      
  66.      /** Gets be called on closing tags like:
  67.       * </tag> */
  68.      @Override
  69.      public void endElement(String namespaceURI, String localName, String qName)
  70.                throws SAXException {
  71.           if (localName.equals("channel")) {
  72.                this.in_outertag = false;
  73.           }else if (localName.equals("item")) {
  74.                this.in_innertag = false;
  75.           }else if (localName.equals("title")) {
  76.                this.in_mytag = false;
  77.           }else if (localName.equals("url")) {
  78.               this.in_url = false;
  79.           }
  80. //          }else if (localName.equals("tagwithnumber")) {
  81. //               // Nothing to do here
  82. //          }
  83.      }
  84.      
  85.      /** Gets be called on the following structure:
  86.       * <tag>characters</tag> */
  87.      @Override
  88.     public void characters(char ch[], int start, int length) {
  89.           if(this.in_mytag){
  90.           myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
  91.      }
  92. //          if(this.in_url){
  93. //              myParsedExampleDataSet.setExtractedString(new String(ch, start, length));
  94. //         }
  95.     }
  96. }
Parsed in 0.043 seconds, using GeSHi 1.0.8.4
Arawass
Freshman
Freshman
 
Posts: 3
Joined: Mon Apr 12, 2010 1:14 am

Postby Buts » Mon May 03, 2010 11:24 pm

First of all: thanks a lot for everything in this topic. I've only been developing Android for one week, but have learned so much from forums and topics like this.

I've read every page of this topic and I notice that a lot of people have the same problem that I'm facing, but the solution is not exactly given. I would like to ask one of you, to post a working application with the solution to the following problem (I've simplified it for easier understanding).

XML:
Code: Select all
<friends>
<person>
<name>Jack</name>
<phone>111-111-111</phone>
</person>
<person>
<name>John</name>
<phone>222-222-222</phone>
</person>
</friends>


Now, using the code in this topic, we will get John's name and John's number. Because at every person, the previous data is overwritten. We will always get the last person in the list.
I know that we need to use an array to store all the persons in the list. I've tried to get that to work, but it just doesn't. I can't seem to get the array available in the main .java source.

Can someone please show us how to store all the persons in an array and output every person using something like a for-loop? Just to show that the names and numbers are in the array.

Output should be something like:
Code: Select all
John
111-111-111
Jack
222-222-222


Thank you so much!
Buts
Freshman
Freshman
 
Posts: 2
Joined: Mon May 03, 2010 3:38 pm

Postby padde » Tue May 04, 2010 12:35 am

XMLDemo.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.xmldemo;
  2.  
  3. import java.util.Vector;
  4.  
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.widget.TextView;
  8.  
  9. public class XMLDemo extends Activity {
  10.     private Vector<Person> friends;
  11.        
  12.     public void onCreate(Bundle savedInstanceState) {
  13.         super.onCreate(savedInstanceState);
  14.         setContentView(R.layout.main);
  15.        
  16.         friends = PersonParser.parse(getResources().openRawResource(R.raw.test));
  17.        
  18.         TextView tv = (TextView) findViewById(R.id.output);
  19.         for(Person p : friends) tv.append(p.toString()+"n");
  20.     }
  21. }
  22.  
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


Person.java
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package de.padde.xmldemo;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Vector;
  6.  
  7. import javax.xml.parsers.ParserConfigurationException;
  8. import javax.xml.parsers.SAXParser;
  9. import javax.xml.parsers.SAXParserFactory;
  10.  
  11. import org.xml.sax.Attributes;
  12. import org.xml.sax.InputSource;
  13. import org.xml.sax.SAXException;
  14. import org.xml.sax.XMLReader;
  15. import org.xml.sax.helpers.DefaultHandler;
  16.  
  17. public class Person {
  18.     private String name;
  19.     private String phone;
  20.    
  21.     public void setName(String n) { this.name = n; }
  22.     public void setPhone(String p) { this.phone = p; }
  23.     public String getName() { return this.name; }
  24.     public String getPhone() { return this.phone; }
  25.    
  26.     public String toString() {
  27.         return "Person[Name: "+this.name+", Phone: "+this.phone+"]";
  28.     }
  29. }
  30.  
  31. class PersonParser {
  32.     public static Vector<Person> parse(InputStream in) {
  33.         SAXParserFactory spf = SAXParserFactory.newInstance();
  34.         SAXParser sp;
  35.         try {
  36.             sp = spf.newSAXParser();
  37.             XMLReader xr = sp.getXMLReader();
  38.             PersonHandler ch = new PersonHandler();
  39.             xr.setContentHandler(ch);
  40.             xr.parse(new InputSource(in));
  41.             return ch.getParsedPersons();                
  42.         } catch (ParserConfigurationException e) {
  43.         } catch (SAXException e) {
  44.         } catch (IOException e) {}
  45.         return null;
  46.     }
  47. }
  48.  
  49. class PersonHandler extends DefaultHandler {
  50.     private enum TAGS { friends, person, name, phone }    
  51.     private StringBuffer tempString;
  52.     private Person tempPerson;
  53.     private Vector<Person> friends;
  54.    
  55.     public PersonHandler() {
  56.         super();
  57.         this.friends = new Vector<Person>();
  58.         this.tempString = new StringBuffer();
  59.     }
  60.    
  61.     public Vector<Person> getParsedPersons() { return friends; }
  62.  
  63.     public void startDocument() { }
  64.     public void endDocument() { }
  65.    
  66.     public void characters(char ch[], int start, int length) {
  67.         tempString.append(ch,start,length);
  68.     }
  69.    
  70.     public void startElement(String n, String l, String q, Attributes a) {
  71.         switch(TAGS.valueOf(l)) {
  72.             case person: tempPerson = new Person(); break;    
  73.             default: tempString.setLength(0); break;
  74.         }
  75.     }
  76.      
  77.     public void endElement(String n, String l, String q) {
  78.         switch(TAGS.valueOf(l)) {
  79.             case name: tempPerson.setName(tempString.toString()); break;
  80.             case phone: tempPerson.setPhone(tempString.toString()); break;        
  81.             case person: friends.add(tempPerson); break;
  82.             default: break;
  83.         }    
  84.     }
  85. }
  86.  
Parsed in 0.045 seconds, using GeSHi 1.0.8.4


res/layout/main.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.    android:orientation="vertical"
  4.    android:layout_width="fill_parent"
  5.    android:layout_height="fill_parent">
  6.    
  7.     <TextView
  8.        android:id="@+id/output"  
  9.        android:layout_width="fill_parent"
  10.        android:layout_height="wrap_content"
  11.    />
  12. </LinearLayout>
  13.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4


res/raw/test.xml
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <friends>
  3.     <person>
  4.         <name>Jack</name>
  5.         <phone>111-111-111</phone>
  6.     </person>
  7.     <person>
  8.         <name>John</name>
  9.         <phone>222-222-222</phone>
  10.     </person>
  11. </friends>
  12.  
Parsed in 0.002 seconds, using GeSHi 1.0.8.4
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby DaggieBe » Tue May 04, 2010 7:50 am

padde wrote:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.     public void endElement(String n, String l, String q) {
  2.         switch(TAGS.valueOf(l)) {
  3.             case name: tempPerson.setName(tempString.toString()); break;
  4.             case phone: tempPerson.setPhone(tempString.toString()); break;        
  5.             case person: friends.add(tempPerson); break;
  6.             default: break;
  7.         }    
  8.     }
  9. }
  10.  
Parsed in 0.035 seconds, using GeSHi 1.0.8.4



Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.    friends.add(tempPerson)
  2.  
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


This will cause an OOME if you parse larger XML files. Heap space is never freed.
DaggieBe
Freshman
Freshman
 
Posts: 5
Joined: Tue May 04, 2010 7:46 am

Postby padde » Tue May 04, 2010 8:50 am

Large XML Files will always end up with an OOME.. so whats the point?
Its an example of a way to deal with what Buts wanted and keep the
parsed data available.

If you have a version thats running better with large files feel free to post.
padde
Master Developer
Master Developer
 
Posts: 443
Joined: Wed Apr 08, 2009 4:52 pm

Postby Beneesh » Tue May 04, 2010 10:17 am

Hi plusminus,


How do we replace the contents of an xml file and saving it? It will be very helpful while editing xml files.



Thanks in advance
Beneesh
Beneesh
Developer
Developer
 
Posts: 26
Joined: Tue Apr 06, 2010 8:18 am
Location: Kerala,India

Postby DaggieBe » Tue May 04, 2010 12:31 pm

padde wrote:Large XML Files will always end up with an OOME.. so whats the point?
Its an example of a way to deal with what Buts wanted and keep the
parsed data available.

If you have a version thats running better with large files feel free to post.


It's not the XML parsing that causes memory issues, it's the Vector<Friends> that will cause problems. You can verify this by removing the Vector and parsing a large XML-file a couple of times. Memory will be freed after endDocument is called.

If you have to parse large XML files, or parse several XML files, or if parsing XML is a core part of your application (eg. a newsreader) my suggestion would be to store the objects in a database and retrieve them when needed.

This is not an Android problem, but more a design 'issue' in SAX. You will encounter it sooner in Android applications as the application only has 16/24Mb of heap. SAX wasn't build to store the complete XML-file, but gives you the opportunity to 'do something' after every endElement (like persisting it in a database).
DaggieBe
Freshman
Freshman
 
Posts: 5
Joined: Tue May 04, 2010 7:46 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 5 guests