Develop weather software for Android (3) and weather for android
It takes nearly half a month to develop the Android weather software together in the previous article. I am sorry that there has been no update due to something. It will speed up the update process recently, we strive to write this series of blog posts before March 13, 2015. In the previous chapter, we have used the LitePal framework to build the databases we need, the content of this chapter will mainly complete network communication operations on getting data from www.weather.com. Anyone who has previously learned about Android development should know that, android provides two main methods to implement Internet communication: HTTPURLCONNECTION and HttpClient. Today we will use different methods than the above two, use the Volley framework to complete our network communication service.
Volley framework is a new network communication framework launched at the Google I/O conference in 2013. Volley is very simple and easy to use, and has also been significantly adjusted in terms of communication performance. Its design goal is to be very suitable for performing a small amount of data, but frequent network operations, it is also suitable for our software.
1. How to obtain data and obtain information from all provinces in China. 01 | Beijing, 02 | Shanghai, 03 | Tianjin, 21 | Zhejiang, etc. We can see that the city and its code are separated by the number |, and the province and province are separated by the number, remember this structure. Then, the regular expression is used to intercept the data. How to view information about cities in Zhejiang Province is actually very simple. You only need to visit the following website: Hangzhou, 2102, Ningbo, 2103, and Wenzhou. In the same way, if you want to access the information of counties and cities below Hangzhou, you only need to add 2101 to the city, as shown in http://www.weather.com.cn/data/list3/city2101.xml. Now we can know how to obtain information about provinces, cities, and cities nationwide, and how to obtain the weather in a specific city? Take Hangzhou City as an example. His County Code is 210101. Visit http://www.weather.com.cn/data/list3/city210101.xmlto return a simple data 210101 | 101210101, followed by the weather code corresponding to Hangzhou City, then we can use the code we get to visit the following website Region. {"Weatherinfo": {"city": "Hangzhou", "cityid": "101210101", "temp1": "1 ℃", "temp2": "10 ℃ ", "weather": "Cloudy to clear", "img1": "n1.gif", "img2": "d0.gif", "ptime": "18:00 "}}
2. How to Implement Network Communication we now know the specific address of the accessed website, so how can we implement real network communication through our software, next, I will first use the HTTPURLCONNCTION method to obtain network data. The specific code is as follows.
Package com. melhc. util; import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. URL; public class HttpUtil {/** obtain provincial and municipal data from the server */public static void sendHttpRequest (final String address, final HttpCallbackListener listener) {new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubHttpURL Connection connection = null; try {// create a url object URL = new url (address); // obtain the HTTPURLCONNCETION instance connection = (HttpURLConnection) URL through the url object. openConnection (); // set the method used by the http request to the get method connection. setRequestMethod ("GET"); // you can customize attributes, such as setting connection timeout and reading timeout in milliseconds. setConnectTimeout (8000); connection. setReadTimeout (8000); // get the InputStream in = connection. getInputStream (); // Replace the input stream with the String BufferedRead Er reader = new BufferedReader (new InputStreamReader (in, "UTF-8"); StringBuffer response = new StringBuffer (); String line; while (line = reader. readLine ())! = Null) {response. append (line);} LogUtil. I ("HTTPUtil", "------------------>" + response. toString (); if (listener! = Null) {listener. onFinish (response. toString () ;}} catch (Exception e) {// TODO: handle exceptionif (listener! = Null) {listener. onError (e) ;}} finally {if (connection! = Null) {connection. disconnect () ;}}}). start ();}}
The above code should be relatively simple and easy to understand, because network communication operations are time-consuming operations, so they cannot be used in the main thread, So we opened a new sub-thread to get data! Careful friends will find that in addition to the target access URL, the above input parameters also include an HttpCallBackListener object. Why is this used? A callback mechanism is used here, because the subthread does not allow return objects, and the data we return may be used in another class, so how to pass the data in two classes will be applied to the callback mechanism. First, create an HttpCallBackListener interface.
Package com. melhc. util;/** interface for returning network connection */public interface HttpCallbackListener {void onFinish (String response); void onError (Exception e );}
Then, this method is passed into our network communication class as a parameter. In fact, its implementation method is the same as that of the onCLickListener commonly used in Android, then, the specific implementation of this interface is implemented in the place where this class is used to obtain the data obtained in network communication. This interface actually becomes a bridge connecting the two classes.
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {@Overridepublic void onFinish(String response) {// TODO Auto-generated method stubboolean result = false;if ("province".equals(type)) {result = Utility.handleProvicesResponse(weatherDB, response);} else if ("city".equals(type)) {result = Utility.handleCitiesResponse(weatherDB, response,selectedProvince);} else if ("county".equals(type)) {result = Utility.handleCountiesResponse(weatherDB,response, selectedCity);}
This is the use of specific implementation classes. This class will be introduced in the Post-blog. Here we only need to pay attention to the fact that we have instantiated the HttpCallBackListener interface in the main thread, the following method is continued through the transmission of the response parameter. The traditional network communication method is over now. Do you still think it is quite troublesome? You have to use any callback mechanism, which is not needed in Volley. People have encapsulated it for us. 3. Volley implements network communication. Next, we will officially use Volley to complete the same communication process as above. It takes only three steps to complete network transmission and response! First, download the Volley jar file and import it to your program! Volley. jar: http://download.csdn.net/detail/u013900875/8279223. Next, take the following three steps!
1. Create a RequestQueue object.
2. Create a StringRequest object.
3. Add the StringRequest object to RequestQueue.
The specific code implementation is as follows:
RequestQueue mQueue = Volley. newRequestQueue (getApplicationContext (); StringRequest stringRequest = new StringRequest (address, new Response. listener <String> () {@ Overridepublic void onResponse (String response) {LogUtil. I ("TAG", "---------------->" + response); boolean result = false; if ("province ". equals (type) {result = Utility. handleProvicesResponse (weatherDB, response);} else if ("city ". equals (type )) {Result = Utility. handleCitiesResponse (weatherDB, response, selectedProvince);} else if ("county ". equals (type) {result = Utility. handleCountiesResponse (weatherDB, response, selectedCity);} if (result) {// return the main thread processing logic runOnUiThread (new Runnable () {@ Overridepublic void run () through the runonUiMainThread Method () {// TODO Auto-generated method stubcloseProgressDialog (); if ("province ". equals (type) {queryProvinces ();} else If ("city ". equals (type) {queryCities ();} else if ("county ". equals (type) {queryCounties () ;}}}}}, new Response. errorListener () {@ Overridepublic void onErrorResponse (VolleyError error) {LogUtil. I ("TAG", "-------------------->" + error); runOnUiThread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method // stub // closeProgressDialog (); Toast. makeText (getApplicationContext (), "add Failed to load data! ", Toast. LENGTH_SHORT). show () ;}) ;}}); mQueue. add (stringRequest );
We can find that the volley framework is much simpler. We don't need to set some HTTP Communication attributes and some callback methods, so we only need to care about how to process the returned data, next we will explain each step of volley's three-step operations one by one.
RequestQueue mQueue = Volley.newRequestQueue(context);
First, you must obtain a RequestQueue object. Note that the RequestQueue obtained here is a request queue object, which can cache all HTTP requests and then send these requests concurrently according to certain algorithms.
StringRequest stringRequest = new StringRequest(address, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("TAG", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", error.getMessage(), error); } });
Step 2: Send an http request. Three parameters must be input. The first parameter is the URL of the target website to be accessed, and the second parameter is the method after data is successfully called back, the third is the method for obtaining data through failure callback. Isn't it very easy? It saves the process of creating interfaces.
mQueue.add(stringRequest);
Finally, add this StringRequest object to RequestQueue! All right, the content of this lesson is here. I hope you can continue to support this series of blog posts. Your support is the greatest motivation for me to write it! The content of today's network communication is over, and the next blog will soon meet you. Below is the application's Git Open Source Address, https://github.com/melhc/SimpleWeather