Android JSON parsing usage summary (iii)-implementation of Three-level City linkage
Source: Internet
Author: User
<span id="Label3"></p><p><p><span style="font-size:18px"></span></p></p><pre name="code" class="java"><pre name="code" class="java">/** * Crazyandcoder * contact: * QQ : 275137657 * email: [email protected] * Reprint please indicate the source! */ </pre></pre><p><p></p></p><p><p><span style="font-size:18px"><br></span></p></p><p style="text-align:center"><p style="text-align:center"><span style="font-size:18px"><span style="font-size:24px">The realization of Three-level city linkage</span><br></span></p></p><p><p></p></p><p><p><span style="font-size:18px">The so-called Three-tier City selection linkage means that when we select a province, all the cities in that province will appear, and when we choose one of them, there will be all the areas under that city, if Any. In this case, the main use of JSON parsing, file I/O flow, Android spinner control and other knowledge points, record the implementation process, easy to refer to later Reference.</span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px">Level three city linkage must not have the address information of various regions of our country, the data in this example is placed in the JSON format in the project assets directory, and then through the resolution can be, do not need us directly in the res/values/array.xml, this can reduce a lot of code. first, Let's look at the contents of the City's JSON format file:</span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px">From the above file we can clearly see the Country's city names in JSON Format. We can parse the file and put it in the spinner to display it.</span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px">Here's how this is achieved:</span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p></p></p><p><p><span style="font-size:18px"><strong>first, The Code Analysis</strong></span></p></p><p><p>the <span style="font-size:18px">layout is simple, a textview is used to display the selected address information, and three spinner are used to load the provincial, city, and District address data respectively. The code will not be Posted. Let's look directly at the main class. </span> <span style="font-size:18px">because we put the provincial data in the file, so the first step is to read it out and parse it into a string type of data, easy to use BELOW. The method of reading local resources is unified, unfamiliar words can refer to the previous blog:</span></p></p><p><p><span style="font-size:18px">Understanding of the<span style="color:rgb(85,85,85); font-family:‘microsoft yahei‘; line-height:35px; text-align:center">Java flow concept</span></span></p></p><p><p><span style="font-size:18px">Directly on the Code:</span></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">/** * Read City JSON file from asset directory into string type * * @Title: initdata * @param * @return void * @throws @date * [August 21, 2015 morning 9:40:00] */private String initdata () {stringbuffer sb = new StringBuffer (); Assetmanager Massetmanager = this.getassets (); try {inputstream is = massetmanager.open ("city.json"); byte[] data = new BYT e[is.available ()];int len = -1;while ((len = is.read (data))! =-1) {sb.append (new String (data, 0, len, "gb2312"));} Is.close (); return sb.tostring ();} Catch (ioexception e) {e.printstacktrace ();} Return null;}</pre></pre><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px">Next we will read the above data to parse, is also the focus of this article, we carefully analyze the parsing process, parsing the data format is quite complex, the array contains an ARRAY. </span> <span style="font-size:18px">First we have to define a few variables so that we can store the data in the provinces and Cities. </span></p></p><p><p><span style="font-size:18px"></span></p></p><pre name="code" class="java"><pre name="code" class="java"> Province private string[] mprovincedatas;//city private string[] mcitiesdatas;//area private string[] mareadatas;// List of selected provinces private string Selectedpro = "";p rivate string selectedcity = "";p rivate string selectedarea = ";p rivate Spinner Mprovincespinner;private Spinner mcityspinner;private Spinner mareaspinner;private arrayadapter<string> Mprovinceadapter;private arrayadapter<string> mcityadapter;private arrayadapter<string> mAreaAdapter;/ /stores all municipalities private map<string, string[]> Mcitiesdatamap = new hashmap<string, string[]> ();// All zones corresponding to the storage City private map<string, string[]> mareadatamap = new hashmap<string, string[]> ();</pre></pre><span style="font-size:18px"><span style="font-size:18px"> </span></span><p><p></p></p><p><p><span style="font-size:18px">01~06: the defined array is used to store information about provinces and Cities.</span></p></p><p style="font-size:18px"><p style="font-size:18px"></p></p><p style="font-size:18px"><p style="font-size:18px"><span style="font-size:18px">09~11 <span style="font-size:18px"></span> : The defined variables are used to store the data of the provinces and cities we select through spinner</span></p></p><p style="font-size:18px"><p style="font-size:18px"><span style="font-size:18px">21~24 <span style="font-size:18px"></span> : A defined variable is used to store all the city information and the corresponding region information that we select for a province.</span></p></p><p><p><br></p></p><span style="font-size:18px"><span style="font-size:18px">Next we analyze the parsing process in detail</span></span><p><p></p></p><p><p><span style="font-size:18px"></span></p></p><pre name="code" class="java"> /** * Start parsing City Data * * @Title: beginjsoncitisdata * @param * @return void * @throws @date * [August 21, 2015 Noon 10:02:23] */private void Beginjsoncitisdata (String Cityjson) {if (! Textutils.isempty (CITYJSON)) {try {jsonobject object = new Jsonobject (cityjson); Jsonarray array = Object.getjsonarray ("citylist");//number of provinces acquired Mprovincedatas = new String[array.length ()]; String mprovincestr = Null;//loops through for (int i = 0; i < array.length (); I++) {//loops through the provinces and saves the province in mprovincedatas[] jsonobject Mprovinceobject = Array.getjsonobject (i), if (mprovinceobject.has ("p")) {mprovincestr = mprovinceobject.getstring ("p" ); mprovincedatas[i] = mprovincestr;} else {mprovincedatas[i] = "unknown province";} Jsonarray cityarray; String mcitystr = Null;try {//loops through the province corresponding to the city Cityarray = Mprovinceobject.getjsonarray ("c");} catch (Exception e) {e.printsta Cktrace (); continue;} Mcitiesdatas = new String[cityarray.length ()];for (int j = 0; J < cityarray.length (); J + +) {//loop through the city and save the city in Mcitiesdat as[] Jsonobject McityObject = Cityarray.getjsonobject (j), if (mcityobject.has ("n")) {mcitystr = mcityobject.getstring ("n"); mcitiesdatas[j] = mcitystr;} else {mcitiesdatas[j] = "unknown city";} Loop traversal Area Jsonarray Areaarray;try {//to Determine if there is a third-level zoning, if not, then jump out of this loop, re-execute the loop traversal city Areaarray = Mcityobject.getjsonarray ("a");} Catch (Exception e) {e.printstacktrace (); continue;} Performing the following procedure indicates that there is a tertiary zone Mareadatas = new String[areaarray.length ()];for (int m = 0; m < areaarray.length (); M++) {//loop through the third level area, and save the area in mareadatas[] jsonobject areaobject = areaarray.getjsonobject (m); if (areaobject.has ("s")) {mareadatas[m] = Areaobject.getstring ("s");} else {mareadatas[m] = "unknown area";} LOG.D (TAG, mareadatas[m]);} All Third-level regional mareadatamap.put (mcitystr, Mareadatas) corresponding to the storage city;} All City mcitiesdatamap.put (mprovincestr, Mcitiesdatas) corresponding to the storage province;}} Catch (jsonexception e) {e.printstacktrace ();}}}</pre><span style="font-size:18px"><span style="font-size:18px">The above code in fact has been commented out in detail, we will carefully analyze the Record.<br></span></span><br><p><p><span style="font-size:18px"><span style="font-size:18px">Line</span> : We first get the root node to parse, from the City.json file we can clearly see that the root node is an array type. The content of the array is the province information we Need.</span></p></p><p><p><span style="font-size:18px">20~29 <span style="font-size:18px"></span> : Loop through all the provinces and deposit the results of the traversal into the mprovincedatas[].</span></p></p><p><p><span style="font-size:18px">31~49 <span style="font-size:18px"></span> : The corresponding city traversal in each province is stored in the mcitiesdatas[].</span></p></p><p><p><span style="font-size:18px">53~61 <span style="font-size:18px">Line</span> : This piece of code is more important, the main meaning is: for the municipality, it is no third-level zone, so when we traverse the discovery if there is no third-level area, we will skip the city directly, traverse the next City.</span></p></p><p><p><span style="font-size:18px">63~75 <span style="font-size:18px"></span> : This section iterates through the tertiary zone and deposits the results of the traversal into the mareadatas[].</span></p></p><p><p><span style="font-size:18px">The <span style="font-size:18px">line</span> : City and Region one by one correspond. It is convenient to get the data of the region corresponding to the city by the city Later.</span></p></p><p><p><span style="font-size:18px">The <span style="font-size:18px"></span> following: provinces and cities one by one correspond. It is convenient to obtain data for the city corresponding to the province by the Province.</span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px">The above is the whole process of parsing, comments or more detailed, the next is relatively simple. Put the parsed results into the adapter in the spinner to display the Data. Here's the adapter we choose Arrayadapter.</span></p></p><p><p><span style="font-size:18px"></span></p></p><pre name="code" class="java">Mprovinceadapter = new Arrayadapter<string> (this, android. r.layout.simple_spinner_item, mprovincedatas); Mprovinceadapter.setdropdownviewresource (android. r.layout.simple_spinner_dropdown_item); Mprovincespinner.setadapter (mprovinceadapter);// Province Select Mprovincespinner.setonitemselectedlistener (new onitemselectedlistener () {@Overridepublic void onitemselected ( adapterview<?> parent, View view, int position, long Id) {selectedpro = ""; Selectedpro = (String) parent.getselected Item ();//update City Area information updatecity (selectedpro) according to province; LOG.D (TAG, "mprovincespinner has excuted!" + "selectedpro is" + selectedpro);} @Overridepublic void onnothingselected (adapterview<?> Parent) {}});// City Select Mcityspinner.setonitemselectedlistener (new onitemselectedlistener () {@Overridepublic void onitemselected ( adapterview<?> parent, View view, int position, long Id) {selectedcity = ""; selectedcity = (String) parent.getselect Editem (); Updatearea (selectedcity); LOG.D (TAG, "mcityspinner has excuted!" + "selectedcity is "+ selectedcity);} @Overridepublic void onnothingselected (adapterview<?> Parent) {}});// Zone Select Mareaspinner.setonitemselectedlistener (new onitemselectedlistener () {@Overridepublic void onitemselected ( adapterview<?> parent, View view, int position, long Id) {selectedarea = ""; Selectedarea = (String) parent.getselect Editem (); tv_address.settext ("selected:" + selectedpro + selectedcity + selectedarea); LOG.D (TAG, "mareaspinner has excuted!" + "selectedarea is" + selectedarea);} @Overridepublic void onnothingselected (adapterview<?> Parent) {}});</pre><pre name="code" class="java"> /** * According to the city select the corresponding district * * @Title: Updatearea * @param @param * cities * @return void * @throws @date * [August 21, 2015 PM 3:52:17] */private void Updatearea (String city) {string[] areas = Mareadatamap.get (city);//presence area if (ar EAS = Null) {//presence zone mareaspinner.setvisibility (view.visible); mareaadapter = new Arrayadapter<string> (this, Android. r.layout.simple_spinner_item, areas); Mareaadapter.setdropdownviewresource (android. r.layout.simple_spinner_dropdown_item); Mareaspinner.setadapter (mareaadapter); mareaadapter.notifydatasetchanged (); mareaspinner.setselection (0);} else {tv_address.settext ("selected:" + selectedpro + selectedcity); mareaspinner.setvisibility (view.gone);}} /** * Update City data according to province * * @Title: updatecityandareadata * @param @param * Pro province * @return void * @throws @date * [August 21, 2015 PM 3:20:15] */private void updatecity (String pro) {string[] cities = mcitiesdatamap.get (pro); for (in t i = 0; I < cities.length; I++) {//presence Zone Mcityadapter = newArrayadapter<string> (this, Android. r.layout.simple_spinner_item, cities); Mcityadapter.setdropdownviewresource (android. r.layout.simple_spinner_dropdown_item); Mcityspinner.setadapter (mcityadapter); mcityadapter.notifydatasetchanged (); mcityspinner.setselection (0);}}</pre><br>The overall code comment is detailed, and finally the source code of the entire project is Attached.<p><p></p></p><p><p><span style="font-size:18px">: Jsondemo<br><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p><p><p><span style="font-size:18px"><br></span></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android JSON parsing usage summary (iii)-implementation of Three-level City linkage</p></p></span>
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