Android development parses XML and achieves three-level linkage effect. androidxml
Please respect others' labor achievements. repost the Source: Parse XML for Android development and achieve three-level linkage effect
This example mainly uses XmlPullParser to parse provinces and cities in the XML document, and then binds the data to the Spinner to achieve the effect of three levels of association. For details about XmlPullParser, refer to the article "parsing and generating XML using PULL in Android development.
Run:
Program code:
Core code:
<Pre name = "code" class = "java"> package com. jph. sevice; import java. io. inputStream; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import org. xmlpull. v1.XmlPullParser; import android. OS. handler; import android. OS. message; import android. util. xml;/*** parse the province, city, and district xml * @ author jph * Date: 2014.09.25 */public class PullProvince {public static final int PARSESUCCWSS = 0x2001; private Handler handler; public PullProvince (Handler handler) {// TODO Auto-generated constructor stubthis. handler = handler;}/*** get all provinces and cities and zones * @ author jph * Date: 2014.09.25 */public void getProvinces (final InputStream inStream) {new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {XmlPullParser pullParser = Xml. newPullParser (); pullParser. setInput (in Stream, "UTF-8"); int event; event = pullParser. getEventType (); Map <String, Map <String, List <String >>> provinces = new HashMap <String, Map <String, List <String >>> (); // province Map <String, List <String> cities = null; // city ArrayList <String> areaAll = null; String pName = ""; // province name String cName = ""; // city name String aName = ""; // region name String targetName = ""; // name of the current node while (event! = XmlPullParser. END_DOCUMENT) {targetName = pullParser. getName (); switch (event) {case XmlPullParser. START_TAG: if ("province ". equals (targetName) {// processing province node pName = pullParser. getAttributeValue (0); // current province name cities = new HashMap <String, List <String> ();} else if ("city ". equals (targetName) {// processing city node cName = pullParser. getAttributeValue (0); areaAll = new ArrayList <String> (); // region} else if ("area ". equals (targetName) {// processing region node aName = pullParser. getAttributeValue (0);} break; case XmlPullParser. END_TAG: if (targetName. equals ("area") {areaAll. add (aName);} else if (targetName. equals ("city") {cities. put (cName, areaAll);} else if (targetName. equals ("province") {provinces. put (pName, cities);} break;} event = pullParser. next () ;}message Message = new message (); Message. obj = provinces; // put the parsed data into the message and send it to the main thread message. what = PARSESUCCWSS; handler. sendMessage (message); // notify the main thread that data has been parsed} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}). start ();}}
Activity:
<Pre name = "code" class = "java"> package com. jph. px; import java. io. inputStream; import java. util. list; import java. util. map; import com. jph. sevice. pullProvince; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. app. activity; import android. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemSelectedListener; import android. widget. arra YAdapter; import android. widget. spinner; import android. widget. toast;/*** provincial, municipal, and district-level linkage * @ author jph * Date: 2014.09.25 */public class MainActivity extends Activity {private Spinner province, city, area; private Map <String, Map <String, List <String> data = null;/** current province selected **/privateString currentProvince; /** current selected city **/privateString currentCity; private PullProvince pullProvince; // ** current selected zone ** // privateStrin G currentArea; private Handler mHandler = new Handler () {@ SuppressWarnings ("unchecked") @ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubswitch (msg. what) {case PullProvince. PARSESUCCWSS: // after data parsing, load data = (Map <String, Map <String, List <String>) msg. obj; initData (); break; default: break;} super. handleMessage (msg) ;}}; @ Overrideprotected void onCreate (Bundle savedInstanceStat E) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); province = (Spinner) findViewById (R. id. province); city = (Spinner) findViewById (R. id. city); area = (Spinner) findViewById (R. id. area); pullProvince = new PullProvince (mHandler); InputStream inStream = this. getClass (). getClassLoader (). getResourceAsStream ("province_city.xml"); pullProvince. getProvinces (inStream);}/*** initialize data */private voi D initData () {if (data! = Null) {String [] arrStrings = data. keySet (). toArray (new String [0]); System. out. println (arrStrings); // enter the province information to province Spinnerprovince. setAdapter (new ArrayAdapter <String> (this, android. r. layout. dimensions, arrStrings); currentProvince = getCurrentProvince (); bindCityAdapter (currentProvince); currentCity = getCurrentCity (); bindAreaAdapter (currentCity); setOnItemSelectedListener ();} privat E void bindAreaAdapter (String currentCity) {// TODO Auto-generated method stub // fill the corresponding area to area Spinnerarea according to the currently displayed city. setAdapter (new ArrayAdapter <String> (this, android. r. layout. simple_list_item_multiple_choice, data. get (currentProvince ). get (currentCity);} private void bindCityAdapter (String currentProvince) {// TODO Auto-generated method stub // fill the corresponding city to city Spinnercity based on the currently displayed province. setAdapter (new ArrayAda Pter <String> (this, android. r. layout. simple_list_item_multiple_choice, data. get (currentProvince ). keySet (). toArray (new String [0]);}/*** sets the listener */private void setOnItemSelectedListener () {// TODO Auto-generated method stubprovince. setOnItemSelectedListener (new OnItemSelectedListener () {@ Overridepublic void onItemSelected (AdapterView <?> Arg0, View arg1, int arg2, long arg3) {// TODO Auto-generated method stubcurrentProvince = getCurrentProvince (); bindCityAdapter (currentProvince) ;}@ Overridepublic void onNothingSelected (AdapterView <?> Arg0) {// TODO Auto-generated method stub}); city. setOnItemSelectedListener (new OnItemSelectedListener () {@ Overridepublic void onItemSelected (AdapterView <?> Arg0, View arg1, int arg2, long arg3) {// TODO Auto-generated method stubcurrentCity = getCurrentCity (); bindAreaAdapter (currentCity) ;}@ Overridepublic void onNothingSelected (AdapterView <?> Arg0) {// TODO Auto-generated method stub}); area. setOnItemSelectedListener (new OnItemSelectedListener () {@ Overridepublic void onItemSelected (AdapterView <?> Arg0, View arg1, int arg2, long arg3) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, area. getSelectedItem (). toString (), Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onNothingSelected (AdapterView <?> Arg0) {// TODO Auto-generated method stub});}/** get the current selected province * @ return String: The current province */private String getCurrentProvince () {// TODO Auto-generated method stubreturn province. getSelectedItem (). toString ();}/** get the selected city * @ return String: The selected city */private String getCurrentCity () {// TODO Auto-generated method stubreturn city. getSelectedItem (). toString ();}}
Layout file:
<pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" ><Spinner android:id="@+id/province" android:layout_width="match_parent" android:layout_height="wrap_content" /><Spinner android:id="@+id/city" android:layout_width="match_parent" android:layout_height="wrap_content"/><Spinner android:id="@+id/area" android:layout_width="match_parent" android:layout_height="wrap_content"/><TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content"/></LinearLayout>
Xml parsing for android Development
It seems that you are parsing a lot or less.
If your XML document contains document data (for example, Framemaker documents stored in XML format), DOM is the most natural choice for your solution. If you want to create a system similar to document information management, You have to process a large amount of document data. Datachannel RIO is an example of indexing and organizing information in various types of document resources (such as Word and Excel files ). In this case, DOM is a very suitable program to access the information stored in these documents.
However, if you are mainly dealing with structured data (the serialized JAVA object in XML the equivalent of serialized Java objects in XML), DOM is not the best choice. That is what is appropriate for SAX.
Hi.baidu.com/...7.html
How to parse xml data retrieved from the background by android Developers
Android-three steps for parsing XML data
The specific steps for DOM parsing are as follows:
1. Use DocumentBuilderFactory to create a DocumentBuilderFactory instance
2. Use DocumentBuilderFactory to create DocumentBuilder.
3. Load the XML Document ),
4. Obtain the root node (Element) of the document ),
5. Then, obtain the list (NodeList) of all child nodes in the root node ),
6. Then, obtain the nodes to be read from the subnode list.
The specific processing steps for parsing using SAX are as follows:
1. Create a SAXParserFactory object
2. According to the SAXParserFactory. newSAXParser () method, a SAXParser parser is returned.
3. Get the event source object XMLReader Based on the SAXParser parser
4. instantiate a DefaultHandler object
5. Connect the event source object XMLReader to the event processing class DefaultHandler.
6. Call the parse method of XMLReader to obtain xml data from the input source.
7. Return the data set we need through DefaultHandler.
Basic PULL parsing method:
1: When you navigate to XmlPullParser. START_DOCUMENT, you do not need to process it. Of course, you can instantiate a collection object.
2: When you navigate to XmlPullParser. START_TAG, you can determine whether it is a river tag. If yes, the river object is instantiated and the getAttributeValue method is called to obtain the attribute values in the tag.
3: When you navigate to another label, such as Introduction, you can determine whether the river object is empty. If not, the content in Introduction is retrieved. The nextText method is used to obtain the content of the text node.
4: it will certainly navigate to XmlPullParser. END_TAG. It will end at the beginning. Here we need to determine whether the river end label is used. If yes, the river object is saved in the list set and the river object is set to null.
Comparison and summary of several parsing technologies:
For Android mobile devices, because the device resources are precious and the memory is limited, we need to select the appropriate technology to parse XML, which is conducive to improving the access speed.
1. When processing XML files, DOM parses the XML files into a tree structure and puts them in the memory for processing. When the XML file is small, we can select DOM because it is simple and intuitive. Www.2cto.com
2. SAX uses an event as the parsing XML file mode. It converts an XML file into a series of events, which are determined by different event processors. When the XML file is large, it is reasonable to select the SAX technology. Although the amount of code is large, it does not need to load all XML files into the memory. This is more effective for limited Android memory, and Android provides a traditional method of using SAX and a convenient SAX package.
3. XML pull parsing does not end listening elements like SAX parsing, but completes most of the processing at the beginning. This facilitates reading XML files early and greatly reduces the parsing time. This optimization is especially important for mobile devices with relatively high connection speeds. The XML Pull parser is more effective when the XML document is large but only a part of the document is required.
.. For details, you can view the relevant information .... Remaining full text>