Android Development parsing XML and achieving three-level linkage effect

Source: Internet
Author: User

Please respect other people's labor results, reproduced please specify the Source: Android Development of parsing XML and achieve three-level linkage effect

This example mainly applies xmlpullparser to parse the provinces and cities in the XML document, then binds the data to the spinner to achieve the effect of level three linkage. About Xmlpullparser You can refer to the article "using pull to parse and generate XML" for 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 Province, City, 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 province cities and districts * @author JPH * date:2014.09.25 */public void getprovinces (final InputStream instream) {new Thread (new R Unnable () {@Overridepublic void Run () {//TODO auto-generated method stubtry {xmlpullparser Pullparser = Xml.newpullparser ();p ullparser.setinput (instream, "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)) {//Handle urban Node CNAME = pullparser.getattributevalue (0); areaall = new arraylist<string > ();//region} else if ("area". Equals (TargetName)) {//Process 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;//the parsed data into the message to the main thread message.what=parsesuccwss;handler.sendmessage (message);//notifies the main thread that the data parsing is complete} 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.arrayadapter;import Android.widget.spinner;import android.widget.toast;/** * Province, city, district level three linkage * @author JPH * date:2014.09.25 */public class MainAct Ivity extends Activity {private Spinner province,city,area;private map<string, map<string, list<string> >> data=null;/** Current selection of the province **/privatestring currentprovince;/** current selection of the city **/privatestring Currentcity;private Pullprovince pullprovince;///** Current selected zone **///privatestring currentarea;private Handler mhandler=new Handler () {@ Suppresswarnings ("unchecked") @Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubswitch (MSg.what) {Case pullprovince.parsesuccwss://data parsing completed, loading data data= (map<string, map<string, list<string>> >) msg.obj;initdata (); break;default:break;} Super.handlemessage (msg);}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);p rovince= (Spinner) Findviewbyid (r.id.province); city= (Spinner) Findviewbyid (r.id.city); Area= (Spinner) Findviewbyid (r.id.area);p ullprovince=new pullprovince (mhandler); InputStream instream = This.getClass    (). getClassLoader (). getResourceAsStream ("Province_city.xml"); Pullprovince.getprovinces (instream);} /** * Initialize data */private void InitData () {if (data!=null) {string[]arrstrings= data.keyset (). ToArray (new string[0]); System.out.println (arrstrings);//fill in the province information to province Spinnerprovince.setadapter (new arrayadapter<string> (this Android. r.layout.simple_list_item_multiple_choice,arrstrings)); Currentprovince=getcurrentprovince (); BindCityAdapter ( currentprovince); Currentcity=getcurrEntcity (); Bindareaadapter (currentcity); Setonitemselectedlistener ();}} private void Bindareaadapter (String currentcity) {//TODO auto-generated method stub//fills the corresponding zone to area according to the currently displayed city Spinnerarea.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//fills the city with the corresponding cities according to the currently displayed province Spinnercity.setadapter (New arrayadapter<string> (this, Android. R.layout.simple_list_item_multiple_choice,data.get (currentprovince). KeySet (). ToArray (new string[0]));} /** * Set listener for spinner */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=GETCURRENTPR Ovince (); 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.getsel Ecteditem (). toString (), Toast.length_short). Show (); @Overridepublic void onnothingselected (adapterview<?> arg0) {//TODO auto-generated Method stub}}); /** gets the currently selected province * @return string: Currently selected province */private string getcurrentprovince () {//TODO auto-generated method Stubreturn Prov Ince.getselecteditem (). toString ();} /** get the currently selected city * @return String: Currently 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>






Android Development parsing XML and achieving three-level linkage effect

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.