Parsing XML from the Net - Using the SAXParser

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

Re: Parsing XML from the Net - Using the SAXParser

Postby ricodroid » Thu Jan 13, 2011 5:00 pm

Hi plusminus,

first of all a big thank you for those great tuts as well as for this one! I just have a simple question. I would like to use this example with a ListActivity. I suppose I'd have to use a ListView variable and then after I got the parsed data I'd have to pass it to that variable. Right now I'm stuck with something like

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. private String[] author;
  2.         private int nitems;
  3.         private String query;
  4.  
  5.        
  6.     /** Called when the activity is first created. */
  7.     @Override
  8.     public void onCreate(Bundle savedInstanceState) {
  9.         super.onCreate(savedInstanceState);
  10.  
  11.         //getting classification number parameterized with "id" from previous activity
  12.         Intent intent = getIntent();
  13.         query = intent.getExtras().getString("id");
  14.        
  15.         ListView lv = new ListView(this);
  16.        
  17.                 try {
  18.                         /* Create a URL we want to load some xml-data from. */
  19.                         URL url = new URL("http://multiweb.gesis.org/solr1/select/?q=classification:" + query + "&version=2.2&start=0&rows=10&indent=on");
  20.  
  21.                         /* Get a SAXParser from the SAXPArserFactory. */
  22.                         SAXParserFactory spf = SAXParserFactory.newInstance();
  23.                         SAXParser sp = spf.newSAXParser();
  24.  
  25.                         /* Get the XMLReader of the SAXParser we created. */
  26.                         XMLReader xr = sp.getXMLReader();
  27.                         /* Create a new ContentHandler and apply it to the XML-Reader*/
  28.                         XMLHandler xmlHandler = new XMLHandler();
  29.                         xr.setContentHandler(xmlHandler);
  30.                        
  31.                         /* Parse the xml-data from our URL. */
  32.                         xr.parse(new InputSource(url.openStream()));
  33.                         /* Parsing has finished. */
  34.                        
  35.                         nitems = xmlHandler.nitems;
  36.                         author = new String[nitems];
  37.                        
  38.                         for(int i = 0; i < nitems; i++){
  39.                                 author[i] = xmlHandler.author[i];
  40.                         }
  41.                        
  42.                        
  43.                         /* Our ExampleHandler now provides the parsed data to us. */
  44.                         ParsedExampleDataSet parsedExampleDataSet =
  45.                                                                         xmlHandler.getParsedData();
  46.                        
  47.                         lv.set?!?!
  48.  
  49.                         /* Set the result to be displayed in our GUI. */
  50.                 this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, authors));
  51.  
  52.                        
  53.                 } catch (Exception e) {
  54.  
  55.                         e.getMessage();
  56.                 }
  57.        
  58.  
  59.     }
  60.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Thanks for your reply in advance.

Best Regards
ricodroid
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Dec 08, 2010 2:34 pm

Top

Re: Parsing XML from the Net - Using the SAXParser

Postby arulelvamj » Thu Jan 20, 2011 12:17 pm

hi i am arul i want full coding i am trying so many time but showing null pointer excepter. i cannot showing Textview
arulelvamj
Freshman
Freshman
 
Posts: 5
Joined: Thu Jan 06, 2011 6:30 am

Re: Parsing XML from the Net - Using the SAXParser

Postby rahul9586 » Fri Jan 21, 2011 5:31 am

@ plusminus: How to parse CDATA if present in xml. The XML that is returned from the webservice i need to call has lots of '&' in tag attributes, and the sax parser throws a parse exception for these. Please suggest a walkaround. I found a solution, converting the input stream to string and replacing all '&' with 'and'. But obviously this approach will use up a lot of memory. Is there any other method?
rahul9586
Freshman
Freshman
 
Posts: 5
Joined: Fri Jan 21, 2011 5:15 am

Re:

Postby win_wizardy » Sat Feb 19, 2011 9:02 am

songotho wrote::D sorry padde,

I want some difference tags because I want to get any data where I want.
If I have multiple difference father tags but child tags's the same. And I want get only data in the tag second.
But when I use your function, this output's always the last tag.
How can I do to get data in the tag second?

Thanks,
--Alex

hi, i'm new here and to android too..this tutorial is really helpful to me, thank you so much . but i have a same question like him too, my xml file look like this :
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <Entry>
  2.  
  3.    <Activity>
  4.     <Activity ID="01">
  5.       <Name>sport carnival</Name>
  6.       <Type>sport</Type>
  7.       <Start>1 January 2011</Start>
  8.       <End>7 January 2011</End>
  9.       <Time>09:00:AM</Time>
  10.     </Activity>
  11.  
  12.     <Activity ID="02">
  13.       <Name>book fair</Name>
  14.       <Type>carnival</Type>
  15.       <Start>3 March 2011</Start>
  16.       <End>4 March 2011</End>
  17.       <Time>09:00:AM</Time>
  18.     </Activity>
  19.  </Activities>
  20.  
  21. </Entry>
Parsed in 0.003 seconds, using GeSHi 1.0.8.4


how can i do this?

thank you so much,
win
[size=50]thank you for teaching me[/size]
win_wizardy
Freshman
Freshman
 
Posts: 2
Joined: Wed Feb 16, 2011 6:53 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby joemarieamparo » Mon Feb 21, 2011 6:21 am

Hello,

I've been trying to parse the xml response through HttpResponse but I can't get it done. Can anybody help me get through this. Here's my code:

text = (TextView)findViewById(R.id.text);
HttpURLConnection conn;
boolean result = false;


BufferedReader lResultReader = null;
try {
URI lUri = new URI("http://api.groupjump.com/authentication.php?method=login&apikey=1111111111&username=1@1.com&password=1111111");

// Prepares the request.
HttpClient lHttpClient = new DefaultHttpClient();
HttpGet lHttpGet = new HttpGet();
lHttpGet.setURI(lUri);

// Sends the request and read the response
HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
InputStream lInputStream = lHttpResponse.getEntity().getContent();


/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();

/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);


//this is where i get error. Any alternative ways please:
xr.parse(new InputSource(lTmpResult));

/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
text.append(parsedExampleDataSet.toString());
}
catch(MalformedURLException e){
text.setText("1: "+e.getMessage());
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
text.setText("2: "+e.getMessage());
}
catch(Exception e){
e.printStackTrace();
text.setText("3: "+e.getMessage());
}

I get error on this line:

xr.parse(new InputSource(lTmpResult));

Here is the XML format that I want to parse.
<?xml version="1.0"?>
<callback>
<request>
<authentication>
<status> </status>
<message></message>
<content>
<id> </id>
<sessionkey></sessionkey>
</content>
</authentication>
</request>
</callback>

Please help.

Thanks,
Joemarie Amparo
[url="http://mydailyservings.wordpress.com"]Joemarie Amparo[/url]
joemarieamparo
Freshman
Freshman
 
Posts: 9
Joined: Thu Jan 20, 2011 6:35 am
Location: Cebu, Philippines

Re: Parsing XML from the Net - Using the SAXParser

Postby plokoon » Fri Mar 25, 2011 11:12 pm

Hello

I followed the example and got it working for a simple XML file, however I am now dealing with a bigger XML file and I am having trouble parsing it. Any help is much appreciated because I have been trying for days.

All I am able to do so far is parse each Item (e.g TextItem and ImageItem) and store this in a StringBuffer. I am stuck on trying to store the elements inside the items (like url, text, filename..)

book.xml
Code: Select all
<books.model.Book key="0073a3b22ede9a5b012ede9a5bf50000" owner="1">

<books.model.TextItem key="0073a3b22ede9a5b012ede9a5c060001" owner="1">
<url>
http://www.google.com
</url>
<text>
Test text string
</text>
</books.model.TextItem>

<books.model.ImageItem key="0073a3b22ede9a5b012ede9a5c070002" owner="1">
<url>
http://www.blah.com
</url>
<filename>
0073a3b22ede9a5b012ede9a5c070002.png
</filename>
</books.model.ImageItem>

</books.model.Book>


XMLHandler
Code: Select all
public class XMLHandler extends DefaultHandler {
   
   
    StringBuffer buff = null;
    StringBuffer buffText = null;
    StringBuffer buffImage = null;
       /*
    * fields
    */
   
    private boolean in_books = false;
   
    private boolean in_booksText = false;
      private boolean in_textItemUrl = false;
      private boolean in_textItemText = false;
   
    private boolean in_booksImage = false;
      private boolean in_imageItemUrl = false;
      private boolean in_imageItemPath = false;
   
   
    //create new object
    private XMLDataSet dataSet = new XMLDataSet();
//   public static XMLDataSet dataSet = null;
   
   
    /*
     * getter & setter
     */
    public XMLDataSet getParsedData() {
        return this.dataSet;
    }

    /*
     * methods
     */
    @Override
    public void startDocument() throws SAXException {
         this.dataSet = new XMLDataSet();
    }

    @Override
    public void endDocument() throws SAXException {
         // Nothing to do
    }



    /** Gets called on opening tags like:
     * <tag>
     * Can provide attribute(s), when xml was like:
     * <tag attribute="attributeValue">*/
     @Override
     public void startElement(String namespaceURI, String localName,
             String qName, Attributes atts) throws SAXException {
       
        if (localName.equals("books.model.Book")) {
             buff = new StringBuffer("");
           this.in_books = true;
        }
        else if (localName.equals("books.model.TextItem")) {
            buffText = new StringBuffer("");
            this.in_booksText = true;
       }
        else if (localName.equals("url")) {
            this.in_textItemUrl = true;}
       
        else if (localName.equals("text")) {
            this.in_textItemText = true;} 
       
        else if (localName.equals("books.model.ImageItem")) {
            buffImage = new StringBuffer("");
            this.in_booksImage = true;}
       
        else if (localName.equalsIgnoreCase("url")) {
            this.in_imageItemUrl = true;
        } 
       
        else if (localName.equalsIgnoreCase("filename")) {
            this.in_imageItemPath = true;} 
       
                
    }
   
    /** Gets called on closing tags like:
     * </tag> */
    @Override
    public void endElement(String namespaceURI, String localName, String qName)
              throws SAXException {
   
       if (localName.equals("books.model.Book")) {
            this.in_placebooks = false;
          
       }
       else if (localName.equals("books.model.TextItem")) {
                this.in_booksText = false;
                String idFromXml = buffText.toString();
             if(idFromXml.trim().length()>0)
             dataSet.setBooksText(idFromXml.trim());
       }
        else if (localName.equals("url")) {
            this.in_textItemUrl = false;                 
        }
        else if (localName.equals("text")) {
            this.in_textItemText = false;                 
        }
        else if (localName.equals("books.model.ImageItem")) {
            this.in_booksImage = false;
            String idFromXml = buffImage.toString();
         if(idFromXml.trim().length()>0)
         dataSet.setBooksImage(idFromXml.trim());
        }
       
        else if (localName.equalsIgnoreCase("url")) {
            this.in_imageItemUrl = false;                 
        }     
        else if (localName.equalsIgnoreCase("filename")) {
            this.in_imageItemPath = false;                 
        }
          
           
    }
   
    /** Gets called on the following structure:
     * <tag>characters</tag> */
    @Override
   public void characters(char ch[], int start, int length) {
       
       if(this.in_books){
           buff.append(ch, start, length).toString();
           dataSet.setBooksData(new String (buff));
        }
       
        if(this.in_booksText){
           buffText.append(ch, start, length).toString();
           //dataSet.setBooksText(new String (buffText));
        }
            if(this.in_textItemUrl){
               dataSet.setTextItemURL(new String(ch, start, length));
            }   
            if(this.in_textItemText){
               dataSet.setTextItemText(new String(ch, start, length));
            } 
        
        
       if(this.in_booksImage){
        buffImage.append(ch, start, length).toString();
        //dataSet.setBooksImage(new String (buffImage));
      }     
            if(this.in_imageItemUrl){
               dataSet.setImageItemURL(new String(ch, start, length));
            }
            if(this.in_imageItemPath){
               dataSet.setImageItemPath(new String(ch, start, length));
            }

   } //end of void characters
   
}

plokoon
Freshman
Freshman
 
Posts: 3
Joined: Fri Mar 25, 2011 10:50 pm

Top

Re: Parsing XML from the Net - Using the SAXParser

Postby dreamhawk » Sun Mar 27, 2011 6:50 pm

I am trying to change row:

26 : tv = new TextView(this);
to
TextView tv = (TextView) findViewById(R.id.xmlview);

But when i start the app, i get force close. And R.id.xmlview DOES exist.
Cause, new TextView(this, null, R.id.xmlview); semi-works. Don't style really, but doesnt FC either.
dreamhawk
Freshman
Freshman
 
Posts: 2
Joined: Thu Mar 24, 2011 9:53 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby kristu » Thu Mar 31, 2011 5:31 pm

first of all, thx for the tutorial, its great!

i'm writing an android client, which connects to a server via socket, and parse the xml input. the input contains hungarian letters (for example: ő,ú,í). the server generating an utf-8 encoded xml file.

the input for the parser is setting up like this:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. inputs = new InputStreamReader(mySocket.getInputStream(), "UTF-8");
  2. input = new InputSource(inputs);
  3. input.setEncoding("UTF-8");
Parsed in 0.035 seconds, using GeSHi 1.0.8.4


but it throws exception (invalid token..) when it get a special character.

what's wrong? please help, ty :)
kristu
Freshman
Freshman
 
Posts: 4
Joined: Sat May 08, 2010 8:38 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby zeroARM000 » Tue Apr 05, 2011 11:00 am

does anybody know how to get image or everything else from html tags inside an xml node?

for example
<summary type="html"><![CDATA[<img src="http://earthquake.usgs.gov/images/globes/60_-155.jpg" alt="60.089°N 152.759°W" align="left" hspace="20" /><p>Tuesday, April 5, 2011 04:41:55 UTC<br>Monday, April 4, 2011 08:41:55 PM at epicenter</p><p><strong>Depth</strong>: 98.50 km (61.21 mi)</p>]]></summary>

you see the img src block right?
I'm hoping to get the other informations too...

Regards..
zeroARM000
Freshman
Freshman
 
Posts: 5
Joined: Tue Apr 05, 2011 10:01 am

Re: Parsing XML from the Net - Using the SAXParser

Postby sarans » Thu Apr 07, 2011 8:17 am

Hai,
Im very much new to android can you please explain me how to build a xml file using dom or sax so that i can send that to server.
sarans
Freshman
Freshman
 
Posts: 5
Joined: Mon Dec 20, 2010 12:18 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby avdapps » Tue Apr 12, 2011 5:06 pm

Hello plusminus,
I have a quick question. I am getting http response interms of xml like below:
<?xml version="1.0" encoding="UTF-8"?>
<KassoResponse xmlns="http://schemas.kickapps.com/services/soap" responseType="signInRegisterUser">
<Param paramName="userRequestStatus" paramValue="User signed in."/>
<Param paramName="sessionToken" paramValue="A1B2C3D4E5F6"/>
<Param paramName="transactionId" paramValue="1234567890"/>
<Param paramName="userId" paramValue="33232"/>
<Param paramName="cname" paramValue="http://affiliate.kickapps.com"/>
<Param paramName="userName" paramValue="JohnDoe"/>
<Param paramName="restApiToken" paramValue="JeTSQY4WBkdbGI0Wao/HdVy44l7aTLNc"/>

</KassoResponse>


I am unsure as how to parse the response that has namespace and nodes with paramname and paramvalue.

PI would appreciate your suggestions
avdapps
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Apr 12, 2011 4:59 pm

Re: Parsing XML from the Net - Using the SAXParser

Postby songotho » Wed Apr 13, 2011 4:42 am

avdapps wrote:Hello plusminus,
I have a quick question. I am getting http response interms of xml like below:
<?xml version="1.0" encoding="UTF-8"?>
<KassoResponse xmlns="http://schemas.kickapps.com/services/soap" responseType="signInRegisterUser">
<Param paramName="userRequestStatus" paramValue="User signed in."/>
<Param paramName="sessionToken" paramValue="A1B2C3D4E5F6"/>
<Param paramName="transactionId" paramValue="1234567890"/>
<Param paramName="userId" paramValue="33232"/>
<Param paramName="cname" paramValue="http://affiliate.kickapps.com"/>
<Param paramName="userName" paramValue="JohnDoe"/>
<Param paramName="restApiToken" paramValue="JeTSQY4WBkdbGI0Wao/HdVy44l7aTLNc"/>

</KassoResponse>


I am unsure as how to parse the response that has namespace and nodes with paramname and paramvalue.

PI would appreciate your suggestions


Hi,
You can go back page 5 of this topic, Padde have a example about parsing data with parameters.
Hope you can do your problem.
Alex.
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Sync SQLite/Android database table to remote MySQL database

Postby ajaypatelaj » Fri Apr 15, 2011 7:22 am

Hi all,

I'm trying to make an SQLite database on the first run of a program, with a single table containing 7 rows, which is intended to match up with a table on a MySQL database on a remote server. So my thoughts are:

(1) On first application run only, create the database, the table, and the number of rows with the desired entries.

(2) On all runs (including the first one) poll a remote MySQL database (over PHP) that contains a table with a timestamp column, and if the timestamp conditions are met (i.e. a new entry has been placed in the database), all entries after that will be added into the SQLite database on the Android phone.

If someone can point me in the right direction or give me some basic code for any aspects of this, that'd be great - thanks.
ajaypatelaj
Junior Developer
Junior Developer
 
Posts: 22
Joined: Mon Apr 04, 2011 12:54 pm

Re: Sync SQLite/Android database table to remote MySQL datab

Postby songotho » Fri Apr 15, 2011 7:30 am

ajaypatelaj wrote:Hi all,

I'm trying to make an SQLite database on the first run of a program, with a single table containing 7 rows, which is intended to match up with a table on a MySQL database on a remote server. So my thoughts are:

(1) On first application run only, create the database, the table, and the number of rows with the desired entries.

(2) On all runs (including the first one) poll a remote MySQL database (over PHP) that contains a table with a timestamp column, and if the timestamp conditions are met (i.e. a new entry has been placed in the database), all entries after that will be added into the SQLite database on the Android phone.

If someone can point me in the right direction or give me some basic code for any aspects of this, that'd be great - thanks.


Hi,
U try to not connect with your MySQL database and you will know what is the right direction^^.
Alex
songotho
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Mar 03, 2009 1:59 am

Re: Sync SQLite/Android database table to remote MySQL datab

Postby ajaypatelaj » Fri Apr 15, 2011 8:03 am

Can you please explain me.. i am beginner

songotho wrote:Hi,
U try to not connect with your MySQL database and you will know what is the right direction^^.
Alex
ajaypatelaj
Junior Developer
Junior Developer
 
Posts: 22
Joined: Mon Apr 04, 2011 12:54 pm

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: Google [Bot] and 6 guests