Android development 9: Network Access & amp; Web service development, android development 9 access

Source: Internet
Author: User

Android development 9: Network Access & Web service development, android development 9 access
Preface

Dear friends ~

Join us in today's theme. Today, we will learn more about network access and Web Service Development, learn how to use HttpURLConnection to access WebService, be familiar with multithreading and Handler to update the UI, and use XmlPullParser to parse xml document data, learn how to use the RecyclerView control.

 

Basic knowledge 1. Network Access & Web Service Development

1. Experiment WebService address

(1) In the experiment, the WebService address is: http://ws.webxml.com.cn/WebServices/WeatherWS.asmx? Op = getWeather

Open the WebService website required by the experiment in the browser and you can see the following:

We can see that the query requires two parameters theCityCode (the default parameter is Shanghai) and theUserID. If you use a free WebService, set theUserID to null. Enter the parameter and click "call" to view the return value:

We can see that the returned data is in xml format. We need to use XmlPullParser to extract the information we need.

(2) interested in the website to see how to use WebService: http://www.webxml.com.cn/zh_cn/web_services.aspx free of charge

PS: free users can query up to 50 times within 24 hours and obtain secondary data with an interval greater than 600 ms
(If the test time exceeds the upper limit, replace the network IP address and try again)

 

2. Network Access

In this experiment, HttpURLConnection is used for network access:

(1) Add the network access permission to manifest:

(2) determine whether a network is available: Use ConnectivityManager to obtain all connection management objects of the mobile phone, use manager to obtain NetworkInfo objects, and finally determine whether the current network status is in the connection status.

(3) define the WebService address we need:

(4) use HttpURLConnection to create an http connection, create a URL object, open the connection, and set the access method and time:

(5) write the fields we need to request to the connection in the form of a stream. This step is equivalent to submitting the required parameters to the network connection and requesting network data (similar to form operations in html, submit post data to the server)

(6) convert xml from webpage to string:

Check response in logcat to convert the xml on the website to a string, which facilitates the next step of xml data parsing.

(7) Close connection:

(8) Note: After Android4.0, the http request must enable the subthread and then execute the request by the subthread. Therefore, the code we wrote previously is completed in the subthread, and use XmlPullParser for parsing to get the desired data:

 

3. Handler updates the UI

In the previous experiment, we know that the UI interface cannot be directly modified in the Child thread, and the man-in-the-middle handler needs to modify the UI:

Message mechanism: Responsible for interactive processing between different threads. We first define the Message Type:

Then pass the required content back through the message:

 

4. XmlPullParser parses xml documents

First obtain the XmlPullParser object instance, then set the string to be parsed, and then obtain the required string one by one according to the tag:

Note:

Because the obtained xml string is an array of the string type (ArrayofString), we can also store the String obtained by string (Tag) to the ArrayList <string>, then, it processes the strings in Handler and continuously splits the required strings to update the UI.

Exception Handling Section:

1) when the city name is incorrect: Check whether the retrieved string is "the query result is blank ...."

2) when the second query interval is <600 ms: Check whether the retrieved string is "Found error: free users cannot use high-speed access ...."

3) up to 50 times: Check whether the retrieved string is "Found error: the free user's access within 24 hours exceeds the specified number ...."

 

Ii. Use the RecyclerView Control

RecyclerView is a new component in the support-v7 package, is a powerful slide component, compared with the classic ListView, also has item recycling reuse function. RecyclerView is an upgraded version of ListView. The most prominent feature is its strong scalability and high flexibility.

(1) import the jar package of RecyclerView. Import method:

Http://jingyan.baidu.com/article/e6c8503c7190b7e54f1a1893.html

(2) RecylerView settings

(3) Structure of the Adapter:

package com.example.administrator.ex9;import java.util.ArrayList;import java.util.List;import android.R.integer;import android.content.Context;import android.graphics.Bitmap;import android.support.v7.widget.RecyclerView;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;public class WeatherAdapter  extends RecyclerView.Adapter<WeatherAdapter.ViewHolder>{private ArrayList<Weather>  weather_list;private LayoutInflater  mInflater;public interface OnItemClickLitener{void onItemClick(View view,  int position,Weather item);}private OnItemClickLitener  mOnItemClickLitener;public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener){this. mOnItemClickLitener = mOnItemClickLitener;}public WeatherAdapter(Context context,ArrayList<Weather> items) {super();weather_list = items;mInflater = LayoutInflater.from(context);}@Overridepublic ViewHolder onCreateViewHolder(ViewGroup viewGroup,  int i) {View view =  mInflater.inflate(R.layout. weather_item, viewGroup,  false);ViewHolder holder =  new ViewHolder(view);holder. Date = (TextView)view.findViewById(R.id. date);holder. Weather_description =(TextView)view.findViewById(R.id. weather_description);holder. Temperature = (TextView)view.findViewById(R.id. temperature);return holder;}@Overridepublic void onBindViewHolder( final ViewHolder viewHolder, final int i) {viewHolder. Date.setText( weather_list.get(i).getDate());viewHolder. Weather_description.setText( weather_list.get(i).getWeather_description());viewHolder. Temperature.setText( weather_list.get(i).getTemperature());if ( mOnItemClickLitener !=  null){viewHolder. itemView.setOnClickListener( new View.OnClickListener() {@Overridepublic void onClick(View v) {//  TODO  Auto- - generated method stubmOnItemClickLitener.onItemClick(viewHolder. itemView, i, weather_list.get(i));}});}}@Overridepublic int getItemCount() {return  weather_list.size();}public static class ViewHolder  extends RecyclerView.ViewHolder{public ViewHolder(View itemView) {super(itemView);}TextView  Date;TextView  Weather_description;TextView  Temperature;}}

(3) After obtaining weather_list in Handler, bind adpter:

 

Lab content

To implement a simple weather query application, the specific requirements are as follows:

1) this interface is the main interface after the application is started 2) Click the Search button (if the network is unavailable)

 

3) enter the city name Search (the Network is available and the city name is correct) 4) enter the city name Search (the city name is incorrect)

 

5) Click the quick button (secondary query <600 ms) 6) to query up to 50 times

 

Experiment Process

This experiment mainly implements a simple weather query application and the weather query function. This experiment mainly involves using HttpURLConnection to access WebService, using multithreading and Handler to update the UI, familiar with using XmlPullParser to parse xml document data, and understanding how to use the RecyclerView control. First, write the XML layout file on the interface. Here we need to set an EditText and a search Button, and nest several LinearLayout in a LinearLayout with @ drawable/shape as the background to display different data, next, set a ListView to display the weather details, and finally set a RecyclerView to display the weather overview for the next five days. Two textviews are set in the item interface layout of listview, and three textviews are set in the item interface layout of RecyclerView. The background shape is as follows:

Next, complete the MainActivity. java class. In the class, we will use HttpURLConnection for network access. After the control is initialized, add the network access permission to manifest:

Define the WebService address we need:

Then determine whether a network is available. Here, ConnectivityManager is used to obtain all connection management objects of the mobile phone, and manager is used to obtain NetworkInfo objects. Finally, it is used to determine whether the current network status is in the connection status (written to the search button event ):

In the button event, we also need to use the set time parameter to determine whether the two query intervals are less than 600 ms and whether the input in the query column is blank by using the judgment statement:

The http request needs to enable the Sub-thread. Then, the sub-thread executes the request and uses XmlPullParser for parsing to obtain the desired data:

In the child thread, use HttpURLConnection to create an http connection, create a URL object, open the connection, and set the access method and time settings:

Write the fields we need to request to the connection in the form of a stream. This step is equivalent to submitting the required parameters to the network connection and requesting network data:

The xml obtained from the webpage is converted to a string:

The Message mechanism is used in subthreads to implement interaction between different threads. After defining the message type, pass the required content back through the message:

Close connection:

After the sub-thread executes the request, XmlPullParser parses the xml document, obtains the XmlPullParser object instance, sets the string to be parsed, and obtains the required string one by one according to the tag:

Then, use Handler to update the UI. You cannot directly modify the UI in the Child thread. You need handler to modify the UI:

Generation of updating Toast:

Update city name and update time information (because the xml string we get is an array of the string type (ArrayofString), we can also follow the string (Tag) the obtained String is stored in ArrayList <String> and then processed in Handler ):

When retrieving the data contained in a text box with a background color, we need the StringTokenizer class in Java to continuously split the required strings to update the UI.

StringTokenizer is a string-separated parsing Type and belongs to: Java. util package. In StringTokenizer, all methods are public and the writing format is [modifier] <return type> <method name ([parameter list])> --

Int countTokens (): the number of times the nextToken method is called.
Boolean hasMoreTokens (): returns whether there are delimiters.
Boolean hasMoreElements (): returns whether there are delimiters.
String nextToken (): returns the String from the current position to the next separator.
Object nextElement (): returns the string from the current position to the next separator.
String nextToken (String delim): similar to 4, return results with the specified separator.


You can split the data to update the UI:

When updating information in ListView, we still need to use key-value pairs to save the data:

 

Next, we will use the RecyclerView control to expand the content.

RecyclerView is a new component in the support-v7 package, is a powerful slide component, compared with the classic ListView, also has item recycling reuse function. RecyclerView is an upgraded version of ListView. The most prominent feature is its strong scalability and high flexibility. After importing the jar package of RecyclerView, set RecylerView:

Set the adapter WeatherAdapter as required in the document and store the corresponding data in the Weather class:

When updating the information in recyclerView, obtain the string according to the string (Tag:

In addition, set three string groups to add the weather information for five days to them:

Add the five-day information to weather_list in sequence:

After weather_list is obtained in Handler, bind adpter:

Complete lab ~

 

Lab

 

Other Summary

WebService:

WebService is an API published on the network. It can be called by sending XML, and the results returned by WebService are also XML data.

Why multithreading is required during Android development:

The Service, Activity, and Broadcast we created are all handled by a main thread. Here we can understand it as a UI thread. However, it takes a long time to perform some time-consuming operations, such as reading and writing large files, database operations, and network downloads. In order not to block the user interface, the ANR response Prompt window appears, at this time, we can consider using the Thread to solve the problem.

In this experiment, we also use multithreading and Handler to update the UI.
Reasons for using Handler to update the UI:

(1) If the current thread is not the same as the main thread, an exception will be thrown when updating the UI;
(2) The Activity checks whether the current thread and the main thread are equal in the onResume () method.
Start;
(3) In the newly opened thread, if the UI is directly updated without sleep, no exception will be thrown;
(4) If you sleep and update the UI, an exception will be thrown.

 

Source code download

Click here to download the source code~

 

Note

1. experiment environment:

Operating System Windows 10

Experimental software Android Studio 2.2.1

Virtual Device: Nexus_5X

API: 23

2. The code format is not very strict due to the size of the inserted code box during code pasting. Sorry ~

 

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.