Day 8 part 1, androidpart

Source: Internet
Author: User

Day 8 part 1, androidpart

Day 8 part 1

Analysis of Android Network Programming-xml File Parsing

--- Reprinted with the source: coder-pig


This section introduces:

Without knowing it, this series of blogs has been written for 8th days. Many of my friends have benefited a lot from the feedback.

I am very pleased that Day 8 was intended to parse Android graphics and image processing,

I decided to explain network programming in Android first, because a friend proposed to explain the network.

In Day 8, we will analyze some Android network applications. This blog is intended for beginners,

In addition, in view of the level of the author, it is only an analysis, not an in-depth! In Day 8, we will explain some basic

Network applications, such as downloading network data, images, file xml, Json, and building a simple client to communicate with the server

Mutual! In Part 1, we will explain in detail the common methods of XML parsing and parsing!



This section describes the road map:






Body of this section:


Android interacts with the Internet in three ways:






XML file highlights:




Comparison of common methods for parsing XML in Android:








To parse XML files by using SAX:




Process for parsing XML by using SAX





Core code:

① SaxService. java:

Package com. jay. example. service; import java. util. arrayList; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; import android. util. log; import com. jay. example. bean. person; public class SaxService extends DefaultHandler {private Person person Person; private ArrayList <Person> persons; // The currently resolved element tag private String tagName = null; // triggered when the Start mark of the document is read. Some initialization operations are usually completed here @ Over Ridepublic void startDocument () throws SAXException {this. persons = new ArrayList <Person> (); Log. I ("SAX", "read to the document header and start parsing xml");} // call when reading a start tag. The second parameter is the tag name, the last parameter is the attribute array @ Overridepublic void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {if (localName. equals ("person") {person = new Person (); person. setId (Integer. parseInt (attributes. getValue ("id"); Log. I ("SA X "," Read tag ");} this. tagName = localName;} // process the content read from the xml file. The first parameter is the string content, followed by the starting position and length @ Overridepublic void characters (char [] ch, int start, int length) throws SAXException {// determines whether the current tag is valid if (this. tagName! = Null) {String data = new String (ch, start, length); // read if (this. tagName. equals ("name") {this. person. setName (data);} else if (this. tagName. equals ("age") {this. person. setAge (Integer. parseInt (data) ;}}// end part of the document. Add the object to the link here @ Overridepublic void endElement (String uri, String localName, String qName) throws SAXException {if (localName. equals ("person") {this. persons. add (person); person = null;} this. tagName = null;} // obtain the persons set public ArrayList <Person> getPersons () {return persons ;}}

② ReadXML () method in MainActivity:

Private ArrayList <Person> readxml () throws Exception {// obtain the file resource to create the input stream object InputStream is = getAssets (). open ("persons. xml "); // ① create the XML parsing processor SaxService ss = new SaxService (); // ② get the SAX parsing factory SAXParserFactory = SAXParserFactory. newInstance (); // ③ create the SAX parser SAXParser parser = factory. newSAXParser (); // ④ assign the xml parsing processor to the parser, parse the document, and send the event to the processor parser. parse (is, ss); is. close (); return ss. getPersons ();}






Dom parsing xml files



Xml parsing process by Dom



Core code:

Code for dom parsing xml:

Public static ArrayList <Person> queryXML (Context context) {ArrayList <Person> Persons = new ArrayList <Person> (); try {// ① obtain the factory example of the DOM Parser: documentBuilderFactory dbFactory = DocumentBuilderFactory. newInstance (); // ② obtain the Dom parser DocumentBuilder dbBuilder = dbFactory from the dom factory. newDocumentBuilder (); // ③ read the xml file to be parsed into the Dom parser Document doc = dbBuilder. parse (context. getAssets (). open ("persons2.xml"); System. out. println ("DomImplemention object for processing this document =" + doc. getImplementation (); // ④ get the node list of the element named person in the document NodeList nList = doc. getElementsByTagName ("person"); // ⑤ traverses the set and displays the elements in the Set and the names of child elements for (int I = 0; I <nList. getLength (); I ++) {// parse Element personElement = (Element) nList from the Person Element first. item (I); Person p = new Person (); p. setId (Integer. valueOf (personElement. getAttribute ("id"); // obtain the Note set NodeList childNoList = personElement of name and age in person. getChildNodes (); for (int j = 0; j <childNoList. getLength (); j ++) {Node childNode = childNoList. item (j); // determines whether the subnote type is the element Noteif (childNode. getNodeType () = Node. ELEMENT_NODE) {Element childElement = (Element) childNode; if ("name ". equals (childElement. getNodeName () p. setName (childElement. getFirstChild (). getNodeValue (); else if ("age ". equals (childElement. getNodeName () p. setAge (Integer. valueOf (childElement. getFirstChild (). getNodeValue ();} Persons. add (p) ;}} catch (Exception e) {e. printStackTrace ();} return Persons ;}





Use the pull parser to parse XML files





Sample Code:

To facilitate the demonstration, pack all three parsing methods into one program:

Three methods are used to parse xml files, and the pull parser is used to generate xml files, which are in the data/<package name>/file directory.

You can find the generated xml file.


:



Reference code: Code download















Android development, alert clock problem, how can I set an alert clock at every day to solve the problem of immediate start? Code:

The time you set has passed. That is to say, your sentence has logic problems.
If (calendar. getTimeInMillis ()> calendar. getTimeInMillis ()){
Calendar. set (Calendar. DAY_OF_YEAR, calendar. get (Calendar. DAY_OF_YEAR) + 1 );
}
Do you want to write it like this?
If (System. currentTimeMills ()> calendar. getTimeInMillis ()){...}
There is another point you should pay attention.
The first sentence should be written like this.
Calendar calendar = Calendar. getInstance (Locale. getDefault ());

200: A film (or classic) that can be learned over and over again )!

I personally think:
If you want to improve your English learning through English Content in movies. Similar textbooks are available both in bookstores and on the Internet. The movie courses are very classic!

We recommend you to download it online. Www.verycd.com/topics/2722851/

The main content of the teaching material is:
Chapter 1 history and genre movie history and types
Chapter 2 character and performance roles and performances
Chapter 3 narrative description
Chapter 4 style
Chapter 5 critical perspectives comment
Chapter 6 blockbuster film (the matrix) file: hacker empire
Chapter 7 comedy film (forrest gump) comedy: A ganzheng Chuan
Chapter 8 social drama film (american beauty) social problem film: american beauty
Chapter 9 action film (the bond films) action film: 007 series movies
Chapter 10 film noir/neo-noir (se7en) Black movie and new black movie: Seven Sins
Chapter 11 romance film :( the english patient) Love film: British patient
Chapter 12 gangster film (the godfather) black band: godfather
Chapter 13 war film (apocalypse now) war film: Modern Revelation
Chapter 14 horror film (the shining) horror film: shining
Chapter 15 science fiction film (2001: a space odyssey) science fiction film: 2001: roaming space

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.