开发者

Android: How to retrieve parsed values

开发者 https://www.devze.com 2023-03-02 19:39 出处:网络
I want to retrieved using for loop or while loop in the oncreate method the values I got after parsing my XML File:

I want to retrieved using for loop or while loop in the oncreate method the values I got after parsing my XML File:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<Phonebook>
    <PhonebookEntry>
        <firstname>Michael</firstname> 
        <lastname>De Leon</lastname> 
        <Address>5, Cat Street</Address> 
        <FileURL>http://android.mobishark.com/wp-content/uploads/2009/07/android-developers.png</FileURL> 
    </PhonebookEntry>
    <PhonebookEntry>
        <firstname>John</firstname> 
        <lastname>Smith</lastname> 
        <Address>6, Dog Street</Address> 
        <FileURL>http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg</FileURL> 
    </PhonebookEntry>
    <PhonebookEntry>
        <firstname>Jember</firstname> 
        <lastname>Dowry</lastname> 
        <Address>7, Monkey Street</Address> 
        <FileURL>http://www.techdigest.tv/android.jpg</FileURL> 
    </PhonebookEntry>
</Phonebook>

My Code:

ParsingXML.java

package com.example.parsingxml;

import java.net.URL;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ParsingXML extends Activity {



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         try {
              /* Create a URL we want to load some xml-data from. */
      开发者_如何转开发        URL url = new URL("http://cloud.eacomm.com/jm/sampleXML.xml");
              url.openConnection();
              /* 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);

              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              tv.setText(parsedExampleDataSet.toString());

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }
}

ExampleHandler.java

package com.example.parsingxml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================

     private StringBuilder mStringBuilder = new StringBuilder();

     private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public List<ParsedExampleDataSet> getParsedData() {
          return this.mParsedDataSetList;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     /** Gets be 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("PhonebookEntry")) {
            this.mParsedExampleDataSet = new ParsedExampleDataSet();
        }

     }

     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("PhonebookEntry")) {
               this.mParsedDataSetList.add(mParsedExampleDataSet);
          }else if (localName.equals("firstname")) {
               mParsedExampleDataSet.setfirstname(mStringBuilder.toString().trim());
          }else if (localName.equals("lastname"))  {
              mParsedExampleDataSet.setlastname(mStringBuilder.toString().trim());
          }else if(localName.equals("Address"))  {
              mParsedExampleDataSet.setAddress(mStringBuilder.toString().trim());
          }else if(localName.equals("FileURL")){
              mParsedExampleDataSet.setFileURL(mStringBuilder.toString().trim());
          }
          mStringBuilder.setLength(0);
     }

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          mStringBuilder.append(ch, start, length);
    }
}

ParsedExampleDataSet.java

package com.example.parsingxml;

public class ParsedExampleDataSet {
    private String firstname = null;
    private String lastname=null;
    private String Address=null;
    private String FileURL=null;


    //Firstname
    public String getfirstname() {
         return firstname;
    }
    public void setfirstname(String firstname) {
         this.firstname = firstname;
    }

    //Lastname
    public String getlastname(){
        return lastname;
    }
    public void setlastname(String lastname){
        this.lastname=lastname;
    }

    //Address
    public String getAddress(){
        return Address;
    }
    public void setAddress(String Address){
        this.Address=Address;
    }

    //FileURL
    public String getFileURL(){
        return FileURL;
    }
    public void setFileURL(String FileURL){
        this.FileURL=FileURL;
    }

    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
    }

}

The code above exactly have the ff. output:

[Firstname: Michael
Lastname: De Leon
Address: 5, Cat Street
File URL: http://android.mobishark.com/wp-content/uploads/2009/07/android-developers.png

,Firstname: John
Lastname: Smith
Address: 6, Dog Street
File URL: http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg

,Firstname: Jember
Lastname: Dowry
Address: 7, Monkey Street
File URL: http://www.techdigest.tv/android.jpg

]

The reason I want to do this is I have a download file class for downloading the file in FileURL values.


If I properly understand your question, what you want to do is to loop through your parsedExampleDataSet List when parsing has finished and print out the values held within it. At the moment you're printing the contents of the List using the toString() method which is clearly not ideal. OK.

What I suggest is that you look at using an Iterator. An Iterator is a very useful object that you can get from a List in order to iteratate, or loop over, that List.

http://developer.android.com/reference/java/util/ListIterator.html

What I'm going to type here isn't fully tested or working code; it's just to give you the basic idea.

You first define an Iterator:

Iterator i;

Get the iterator from the List:

i = parsedExampleDataSet.iterator();

Then you can use i.hasNext() to see if the Iterator has any more elements, and you use i.next() to get each element. Each call to .next() causes the Iterator to move to the next item in the list, so usually you need to make a temporary reference to the item. Like this:

ParsedExampleDataSet dataItem;
while(i.hasNext()){

 dataItem = i.next();
 someTextView1.setText(dataItem.getFileURL());
 anotherTextView.setText(dataItem.getAddress());

}

... etc.

Obviously what you do with the Strings returned from .getFileURL(), .getAddress etc. inside the while loop depends on your specific UI. In my little example there, I'm overwriting URLs and addresses into the same TextView; however its purpose is to just demonstrate the concept of looping over your List dataset.

0

精彩评论

暂无评论...
验证码 换一张
取 消