Android tutorial ---- teach you how to build an air quality client in Hebei

Source: Internet
Author: User
Tags xml parser

This article will work with you from scratch to makeHebei Automatic Air Quality Publishing SystemThe article is intended for students who have read only a few Android tutorials. For more basic content, the text will also be marked with the link of the red letter. You can open a detailed introduction.

In fact, it is entirely because of dad that the air quality in Hebei is too bad, so he decided to choose not to take a walk every day based on the air quality. The website is always too complicated, so I had the idea of creating a client. The following steps describeInformation Acquisition,Asynchronous acquisition of network data,Data Analysis,Interface DesignAndProgram LogicThe following describes how a complete program is developed.

First, you need to find the program data source and find the website for obtaining the data interface from the Internet.

Second, we need to convert the data format from the Internet into a usable format.

Next, design the layout, and fill in the data in the layout. The whole program is complete.

The following is the website of this system and the client I am working on:



1. We need to have a data source first to obtain the data. The data is provided by the Hebei provincial environmental monitoring center. Now we need to find its interface. Open URL: Http: // 121.28.49.85: 8080/We can see that this is a flash page, and there is an obvious loading process, indicating that the browser has obtained data. We use HttpAnalyzeOr SmsniffTo view the data packets sent by the browser, of course, the most convenient is to use the Chrome function. Open Chrome --> F12 --> select the NetWork tag --> open the NetWork address above, and there will be a lot of request data below, we press SizeThe largest data we need after sorting is the data we need. For example:

The address of the sent request.

Response
As shown in: After opening the webpage, the browser sends several pieces of data, one of which is larger than other data packages with a size of 59.75 k. We can think that this is the source of data, we can see that it points to the URL http: // 121.28.49.85: 8080/datas/hour/130000.xml. In the reply, the encoding is found to be UTF-8Encoding. Open this URL and we can see the XML data shown in:

Next we will build a client based on the above data.
2. Obtain asynchronous Information 2.1 create an Android project and open an Eclipse with ADT (Android Developer Tools) configured. Tutorial), Select File --> New --> Android Application Project, and Name the program in Application Name, for example, HebeiAir, the SDK for the minimum requirement is API14 (which is not affected if it is lower). Keep the default value for other sdks. After the establishment, our program will have at least the following files:

2.2 asynchronous acquisition of network data in chapter 1, we found the URL for obtaining data. Here, we want to capture the data of this URL for our use. Create a new Class in the src package named Util and define a new static method: HttpGet. This method can simulate browser access. We enter the URL parameter, the function returns the webpage source code:
Public static String HttpGet (String url) throws ClientProtocolException, IOException {// create a default connection DefaultHttpClient client = new DefaultHttpClient (); // create a Get method HttpGet = new HttpGet (url); // obtain the network response HttpResponse response = client.exe cute (get); // obtain the webpage source code (xml) string content = null; // if the server responds with OK! If (response. getStatusLine (). getStatusCode () = 200) {// The following process reads network data in segments: InputStream in = response. getEntity (). getContent (); byte [] data = new byte [1024]; int length = 0; ByteArrayOutputStream bout = new ByteArrayOutputStream (); while (length = in. read (data ))! =-1) {bout. write (data, 0, length);} // finally convert byte to String encoded as utf-8.content = new String (bout. toByteArray (), "UTF-8");} // The returned string is the webpage source code return content ;}

In the Chrome information window above, we can see that the returned value is UTF-8 encoded, so here we use UTF-8 encoding, if we use "gbk" or "gb-2312" here there will be garbled, the codes of each website are different. The specific situation should be analyzed in detail.
Note that this function cannot be directly used in our program, because in Android 4.0, The main thread cannot perform network operations.So we need to start a new thread. In Android, there is a mature class: AsyncTask(Asynchronous task), can complete this work (Thread + Handler is also a method, because our work is relatively simple, do not mention them for the moment ).
Next, we try to display the XML source code.. Create a new class in the MainActivity class GetSourceThis class inherits from AsyncTask to obtain data on the webpage. Logcat(It can be understood as the console on Android:
Class GetSource extends AsyncTask <String, Void, String >{// this function is used to process Background events @ Overrideprotected String doInBackground (String... params) {try {// The download function return Util we just wrote is called here. httpGet ("http: // 121.28.49.85: 8080/datas/hour/130000.xml");} catch (IOException e) {} return null;} // After the background transaction is completed, this function is used to change the interface content @ Overrideprotected void onPostExecute (String result) {// Let the Log output the Log at runtime. I ("test", result );}}

Add the following sentence to the last line of the OnCreate function. Add network PermissionsThen let's see the effect!
new GetSource().execute();

3. UI design our goal is to design the software into the style at the beginning of the article, so we need to simply modify activity_main.xml: · place a TextView on the top, with the background light green, the text color is white. · the lower part is a GridView. The color of each grid varies according to the air quality. The city name is displayed on the top of the grid, and the current AQI is displayed on the bottom. · At the same time, a progress bar of the circle will be displayed on the interface. The code for displaying the progress bar during loading is as follows:
<RelativeLayout 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"    tools:context=".MainActivity" >        <LinearLayout            android:id="@+id/ll"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:visibility="gone"            android:orientation="vertical" >            <TextView                android:id="@+id/tv_time"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_margin="5dp"                android:background="#7a7"                android:padding="5dp"                android:textColor="#eee"                android:textSize="20sp"                android:textStyle="bold" />            <GridView                android:id="@+id/gv"                android:layout_width="match_parent"                android:layout_height="fill_parent"                android:layout_margin="5dp"                android:horizontalSpacing="3dp"                android:verticalSpacing="3dp"                android:numColumns="3" >            </GridView>        </LinearLayout>        <ProgressBar            android:id="@+id/pb1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerHorizontal="true"            android:visibility="visible"            android:layout_centerVertical="true" /></RelativeLayout>

GridViewIt is a grid layout. In the above code, I set the number of grids in each row to three, and set the spacing between grids. The layout in each grid requires another file to control: gv. xml:
<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: id = "@ + id/bg" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: padding = "8dp" android: orientation = "vertical"> <TextView android: id = "@ + id/TV _city" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Shijiazhuang" android: textColor = "# 4bd" android: textSize = "20sp" android: textStyle = "bold"/> <TextView android: id = "@ + id/TV _aqi" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "223" android: textColor = "# 4bd" android: textSize = "18sp" android: textStyle = "bold"/> </LinearLayout>

4. Data Analysis 4.1 Parse XML data obtained on the Internet and convert the XML data to the structured data that we can use. DOM-based XML Parser. Change GetSourceIn OnPostExecuteThe code in is:
@ Overrideprotected void onPostExecute (String result) {// create a parser DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); DocumentBuilder builder; try {builder = factory. newDocumentBuilder (); InputStream is = new ByteArrayInputStream (result. getBytes (); Document document = builder. parse (is); Element element = document. getDocumentElement (); // obtain all Citys node data NodeList cityList = element. getElementsByTagName ("Citys"); // obtain the mapstitle data and split it into two parts: NodeList title = element. getElementsByTagName ("MapsTitle"); String text1 = title. item (0 ). getTextContent (); String t [] = text1.split ("\ ("); text1 = t [0]; t = t [1]. split (","); TV _time.setText (text1 + "\ n" + t [0]); Element citys = (Element) cityList. item (0); NodeList city = citys. getChildNodes (); for (int I = 0; I <city. getLength (); I ++) {// In this case, all data of a city is Node = city on the item of the city node. item (I); if (node. getNodeName (). equalsIgnoreCase ("city") {// This is a valid node CityData cd = new CityData (node); nodeList. add (node); cdList. add (cd) ;}} catch (Exception e ){}

In this way, the data in each city becomes a Node, and the XML parsing process is complicated and requires constant attempts.
4.2 To apply data to the layout, write an Adapter to connect the layout and code. We assume that the data of every city is Node(Node), the data in the GridView exists in a list, and the number of cells is related to the length of the list. (If there are more monitoring sites in Hebei Province, the program can also be changed and adaptive)The XML of the analysis data source can be obtained. What we need is the city and the list of monitoring points in each city. Therefore, create two classes here: CityData, PointerCityData includes a Pointer list. The following is the CityData class. The Pointer class is similar to this one:
Public class CityData implements Serializable {/*** inherits Serializable to pass values on two different interfaces */private static final long serialVersionUID =-8473485404751986234L; // The City class contains the public String name, dataTime, aqi, level, maxPoll, color, intro, tips; public List <Pointer> pointerList; public CityData (Node cityNode) {super (); // extract the content of the corresponding tag one by one. this. name = getByTag (cityNode, "name"); this. dataTime = getByTag (cityNode, "datatime"); this. aqi = getByTag (cityNode, "aqi"); this. level = getByTag (cityNode, "level"); this. maxPoll = getByTag (cityNode, "maxpoll"); String tmp = getByTag (cityNode, "color"); this. color = tmp. replace ("0x", "#"); this. intro = getByTag (cityNode, "intro"); this. tips = getByTag (cityNode, "tips"); Element city = (Element) cityNode; NodeList pointers = city. getElementsByTagName ("Pointer"); // Add the monitoring point pointerList = new ArrayList <pointer> (); for (int I = 0; I <pointers. getLength (); I ++) {Node pNode = pointers. item (I); pointerList. add (new Pointer (pNode) ;}// retrieve the functionprivate String getByTag (node Node, String tag) from the XML node) {for (int I = 0; I <node. getChildNodes (). getLength (); I ++) {if (tag. equalsIgnoreCase (node. getChildNodes (). item (I ). getNodeName () return node. getChildNodes (). item (I ). getTextContent () ;}return null ;}}

Adapter responsible for filling data into the layout:
Class gvAdapter extends BaseAdapter {// the data source of the Adapter. Based on this data, fill in the grid List <CityData> cdList; public gvAdapter (List <CityData> cdList) {super (); this. cdList = cdList;} // return the corresponding value @ Overridepublic int getCount () {return cdList. size () ;}@ Overridepublic Object getItem (int position) {return null ;}@ Overridepublic long getItemId (int position) {return 0 ;}@ Overridepublic View getView (int position, view convertView, ViewGroup parent) {// parse the layout of each previously written grid convertView = MainActivity. this. getLayoutInflater (). inflate (R. layout. gv, null); // locate the elements in the layout and the layout background TextView TV _city = (TextView) convertView. findViewById (R. id. TV _city); TextView TV _aqi = (TextView) convertView. findViewById (R. id. TV _aqi); View bg = convertView. findViewById (R. id. bg); // fill in the content of each grid and the background color TV _city.setText (cdList. get (position ). name); TV _aqi.setText (cdList. get (position ). aqi); bg. setBackgroundColor (Color. parseColor (cdList. get (position ). color); return convertView ;}}

After the XML parsing is complete, add gv. setAdapter (new gvAdapter (cdList) to fill the data in the grid.
5. When you click the item of each GridView in other program logic, the corresponding City Details page is displayed. Right-click the project directory New --> Other --> Activity and name the New Activity CityActivity. Write the layout and logic for the new Activity as described above. Click the grid in the main interface to automatically jump to the new interface:
Gv. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView <?> Parent, View view, int position, long id) {// jump from the current interface to the City Details interface Intent it = new Intent (MainActivity. this, CityActivity. class); // the object itself cannot be passed using Intent, but we inherit Serializable, making it possible to pass. putExtra ("node", cdList. get (position); startActivity (it );}});

1. On the City Details page, click each monitoring point to display the detailed data of the monitoring point. The AlertDialog dialog box is used to display detailed data. 2. Change Res --> values --> string. xmlContent in, to personalize our program, as follows:
<Resources> <string name = "app_name"> Hebei Air Quality </string> <string name = "title_activity_city"> City Data </string> </resources>
In this way, the program name becomes "HEBEI Air Quality". When the detailed information page is displayed, the title bar is also changed to "City Data". 3. Find an image, make the png format and overwrite the res/drawable-hdpi/ic_launcher.png file. In this way, the icon in the mobile APP list is changed.



In fact, it is very simple to make an APP. As long as you have an idea, the above work can be completed within one day. This article mainly aims to give you an idea of how to discover some content around you to make your own apps. May simply look at the explanation will not understand too much, then you can go to http://download.csdn.net/detail/icyfox_bupt/6908053download program source code reprint please indicate from: http://blog.csdn.net/icyfox_bupt/article/details/18953581

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.