C # programmers learn how to call WebService In the Android development series,

Source: Internet
Author: User
Tags define function random seed

C # programmers learn how to call WebService In the Android development series,

The first question I encountered when learning about Android development is how the Android client interacts with the server database? This is a big problem that plagued me when I first came into contact with Android. One day a few years ago, I suddenly thought that WebService was okay? Let the WebService act as the server role to complete operations related to the server database, and the Android client only needs to call according to the WebService method parameters. At that time, I was not vague about the implementation of this solution. I think this problem is also a problem that some Android beginners will surely think. Now let's implement it.

This program demonstrates how to request the Web Service to obtain the data provided by the server.

Since I am familiar with C #, I prefer to use my familiar technologies to build a WebService project. It's easy to use the VS tool to create a Web Service Application (VS2008, and from VS2010, use WCF to create a service application first, however, it is easy to create a WebService using the WCF framework ).

        [WebMethod]        public string DataTableTest()        {            DataTable dt = new DataTable("userTable");            dt.Columns.Add("id",typeof(int));            dt.Columns.Add("name", typeof(string));            dt.Columns.Add("email", typeof(string));            dt.Rows.Add(1, "gary.gu", "guwei4037@sina.com");            dt.Rows.Add(2, "jinyingying", "345822155@qq.com");            dt.Rows.Add(3, "jinyingying", "345822155@qq.com");            dt.Rows.Add(4, "jinyingying", "345822155@qq.com");            return Util.CreateJsonParameters(dt);        }
The WebService method is simple. It is to set up a DataTable data type and convert it to a JSON string through the CreateJsonParameters method. Here, the DataTable can be modified to read data from the database to the DataTable object.

        public static string CreateJsonParameters(DataTable dt)        {            StringBuilder JsonString = new StringBuilder();            if (dt != null && dt.Rows.Count > 0)            {                JsonString.Append("{ ");                JsonString.Append("\"Result_List\":[ ");                for (int i = 0; i < dt.Rows.Count; i++)                {                    JsonString.Append("{ ");                    for (int j = 0; j < dt.Columns.Count; j++)                    {                        if (j < dt.Columns.Count - 1)                        {                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");                        }                        else if (j == dt.Columns.Count - 1)                        {                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");                        }                    }                    if (i == dt.Rows.Count - 1)                    {                        JsonString.Append("} ");                    }                    else                    {                        JsonString.Append("}, ");                    }                }                JsonString.Append("]}");                return JsonString.ToString();            }            else            {                return null;            }        }
This method is a simple method I can find on the Internet. It is just concatenate A JSON string directly (it doesn't matter, this is not the focus of our attention ).

When the WebService end is ready, it can be published to IIS. The publishing method is the same as that of the website. If it is a local machine, you can directly test the WebService method to return the result. For example, after the WebService method is called, the following result is obtained:

Someone may ask, is it XML and JSON in it? Isn't it a "four-character? Yes, I want to explain that WebService is based on Soap, and the data transmission format is XML, so the XML document is taken for granted here. If you want to obtain a pure JSON string, you can use the WCF framework in C # (you can specify the JSON format returned by the client) or the Servlet in Java (directly fl the JSON text ).

Okay. Let's do two things:

1. Request this WebService to obtain the JSON string

2. format the JSON string to display in Android

We will first provide an Assistant class, which is the method I need to manually encapsulate these two operations.

/*** @ Author gary. gu helper class */public final class Util {/*** @ param nameSpace WS nameSpace * @ param methodName WS method name * @ param wsdl WS complete path name * @ param params the parameter * @ return SoapObject */public static SoapObject callWS (String nameSpace, string methodName, String wsdl, Map <String, Object> params) {final String SOAP_ACTION = nameSpace + methodName; SoapObject soapObject = new SoapObject (nameSpace, MethodName); if (params! = Null )&&(! Params. isEmpty () {Iterator <Entry <String, Object> it = params. entrySet (). iterator (); while (it. hasNext () {Map. entry <String, Object> e = (Map. entry <String, Object>) it. next (); soapObject. addProperty (e. getKey (), e. getValue () ;}} SoapSerializationEnvelope envelope = new SoapSerializationEnvelope (SoapEnvelope. VER11); envelope. bodyOut = soapObject; // compatible. web Serviceenvelope. dotNet = true; HttpTranspo RtSE ht = new HttpTransportSE (wsdl); try {ht. call (SOAP_ACTION, envelope); if (envelope. getResponse ()! = Null) {SoapObject result = (SoapObject) envelope. bodyIn; return result;} else {return null ;}} catch (Exception e) {Log. e ("error", e. getMessage ();} return null ;} /***** @ param result JSON String * @ param name JSON array name * @ param fields JSON String contains fields * @ return returns List <Map <String, object> type List, Map <String, Object> corresponds to the "id": "1" structure */public static List <Map <String, object> convertJSON2List (String result, String name, String [] fields) {List <Map <String, Object> list = new ArrayList <Map <String, object >>> (); try {JSONArray array = new JSONObject (result ). getJSONArray (name); for (int I = 0; I <array. length (); I ++) {JSONObject object = (JSONObject) array. opt (I); Map <String, Object> map = new HashMap <String, Object> (); for (String str: fields) {map. put (str, object. get (str);} list. add (map) ;}} catch (JSONException e) {Log. e ("error", e. getMessage () ;}return list ;}}
Tips: we all know how to add comments to methods in C #. You can press "/" three times and generate them automatically by means of. In Eclipse, you can enter "/**" in the method and press enter to generate it automatically.

Public class TestWS extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); RelativeLayout l = new RelativeLayout (this); Button button Button = new Button (l. getContext (); button. setText ("click the local webservice"); l. addView (button); setContentView (l); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {final String nameSp Ace = "http://tempuri.org/"; final String methodName = "DataTableTest"; final String wsdl = "http: // 10.77.137.119: 8888/webserviceTest/Service1.asmx? WSDL "; // call WebService to return SoapObject soapObject = Util. callWS (nameSpace, methodName, wsdl, null); if (soapObject! = Null) {// obtain the value of the DataTableTestResult attribute of the soapObject object String result = soapObject. getProperty ("DataTableTestResult "). toString (); Toast. makeText (TestWS. this, result, Toast. LENGTH_SHORT ). show (); try {// convert the JSON String to the List structure List <Map <String, Object> list = Util. convertJSON2List (result, "Result_List", new String [] {"id", "name", "email "}); // pass the List to the new ActivityIntent newIntent = new Intent (TestWS. this, GridViewTest. class); Bundle bundle = new Bundle (); // List must be a Serializable bundle. putSerializable ("key", (Serializable) list); newIntent. putExtras (bundle); // start the new ActivitystartActivity (newIntent);} catch (Exception e) {e. printStackTrace () ;}} else {System. out. println ("This is null... ");}}});}}

Note the following two points:

1. This Activity does not load the layout file, but creates a Button through the Code. This is also a method for creating views.

2. Using the Intent Object, we pass the List <Map <String, Object> to the new Activity. Pay attention to the value passing method between Intent.

Public class GridViewTest extends Activity {GridView grid; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_gridview); Intent intent = this. getIntent (); Bundle bundle = intent. getExtras (); // obtain the passed List <Map <String, Object> Object @ SuppressWarnings ("unchecked") List <Map <String, object> list = (List <Map <String, Object>) bundle. getSerializable ("key"); // use the findViewById method to find the GridView object grid = (GridView) findViewById (R. id. grid01); // SimpleAdapter adapter fill // 1. the current context of the context, represented by this, or GridViewTest. this // 2. data A List of Maps. it must be a List of the List <Map <String, Object> structure, that is, the data source // 3. resource layout file // 4. where to extract the key from the data source List // 5.to where to go, that is, fill in the control SimpleAdapter adapter in the layout file = new SimpleAdapter (this, list, R. layout. list_item, new String [] {"id", "name", "email"}, new int [] {R. id. id, R. id. name, R. id. email}); // bind the GridView and the adapter to the grid. setAdapter (adapter );}}
First obtain the passed List object, and then bind it to the GridView through SimpleAdapter.

Activity_gridview.xml layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >        <GridView         android:id="@+id/grid01"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:horizontalSpacing="1pt"        android:verticalSpacing="1pt"        android:numColumns="3"        android:gravity="center"/></LinearLayout>
List_item.xml layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:gravity="center_vertical"    android:orientation="vertical" >    <TextView        android:id="@+id/id"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/name"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/email"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>
Complete AndroidManifest. xml configuration:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.webservicedemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="14" />    <uses-permission android:name="android.permission.INTERNET" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".TestWS"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity            android:name=".GridViewTest"            android:label="@string/app_name" >        </activity>    </application></manifest>

Finally, the data obtained from the database server is displayed on the simulator:





C language rand () function

Rand and srand usage
First, we need to have a general opinion on rand & srand: srand initializes random seeds, and rand generates random numbers. The following describes in detail.

Rand (Random Number Generation)
Header file: # include <stdlib. h>

Define function: int rand (void)

Function Description:
Because the internal implementation of rand is made by the linear same remainder method, it is not a real random number, but because its cycle is very long, so it can be considered as random within a certain range, rand () returns a random value ranging from 0 to RAND_MAX. Before calling this function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set, rand () will automatically set the random number seed to 1. Rand () generates false random numbers, which are the same during each execution. To be different, initialize it with different values. The initialized function is srand ().

Return Value:
Returns a random integer between 0 and RAND_MAX. The range of RAND_MAX is at least 32767 (int), that is, double byte (16 digits ). If unsigned int is used, the dual-byte value is 65535, and the four-byte value is an integer range of 4294967295.
0 ~ RAND_MAX the probability of each number being selected is the same.

Example:
/* Generate a random value ranging from 1 to 10. In this example, no random seed is set. For the complete random number generation, see
Srand ()*/
# Include <stdlib. h>
Main ()
{
Int I, j;
For (I = 0; I <10; I ++)
{
J = 1 + (int) (10.0 * rand ()/(RAND_MAX + 1.0 ));
Printf ("% d", j );
}
}
Run:

9 4 8 8 10 2 4 8 3 6
9 4 8 8 10 2 4 8 3 6 // re-execution still produces the same random number

Srand (set Random Seed)
Header file: # include <stdlib. h>

Define the function: void srand (unsigned int seed );

Function Description:
Srand () is used to set the random number seed when rand () generates a random number. The seed parameter must be an integer. Generally, the return value of geypid () or time (0) can be used as seed. If the same value is set for each seed, the random values generated by rand () are the same each time.

Example
/* Generate a random number ranging from 1 to 10. This example and execution result can be referenced with rand */
# Include <time. h>
# Include <stdlib. h>
Main ()
{
Int I, j;
Srand (int) time (0 ));
For (I = 0; I <10; I ++)
{
J = 1 + (int) (10.0 * rand ()/(RAND_MAX + 1.0 ));
Printf ("% d", j );
}
}
Execution: Compare with the rand example
5 8 8 8 10 2 10 8 9 9
2 9 7 4 10 3 2 10 8 7
Or:
Use "int x = rand () % 100;" to generate a random number between 0 and 100. This method is not or can be used. A better method is j = (int) (n * rand ()/(RAND_MAX + 1.0) generates a random number between 0 and n.
Int main (void)
{
Int I;
Time_t t;
Srand (unsigned) time (& t ));
Printf ("Ten r... the remaining full text>

C language rand () function

Rand and srand usage
First, we need to have a general opinion on rand & srand: srand initializes random seeds, and rand generates random numbers. The following describes in detail.

Rand (Random Number Generation)
Header file: # include <stdlib. h>

Define function: int rand (void)

Function Description:
Because the internal implementation of rand is made by the linear same remainder method, it is not a real random number, but because its cycle is very long, so it can be considered as random within a certain range, rand () returns a random value ranging from 0 to RAND_MAX. Before calling this function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set, rand () will automatically set the random number seed to 1. Rand () generates false random numbers, which are the same during each execution. To be different, initialize it with different values. The initialized function is srand ().

Return Value:
Returns a random integer between 0 and RAND_MAX. The range of RAND_MAX is at least 32767 (int), that is, double byte (16 digits ). If unsigned int is used, the dual-byte value is 65535, and the four-byte value is an integer range of 4294967295.
0 ~ RAND_MAX the probability of each number being selected is the same.

Example:
/* Generate a random value ranging from 1 to 10. In this example, no random seed is set. For the complete random number generation, see
Srand ()*/
# Include <stdlib. h>
Main ()
{
Int I, j;
For (I = 0; I <10; I ++)
{
J = 1 + (int) (10.0 * rand ()/(RAND_MAX + 1.0 ));
Printf ("% d", j );
}
}
Run:

9 4 8 8 10 2 4 8 3 6
9 4 8 8 10 2 4 8 3 6 // re-execution still produces the same random number

Srand (set Random Seed)
Header file: # include <stdlib. h>

Define the function: void srand (unsigned int seed );

Function Description:
Srand () is used to set the random number seed when rand () generates a random number. The seed parameter must be an integer. Generally, the return value of geypid () or time (0) can be used as seed. If the same value is set for each seed, the random values generated by rand () are the same each time.

Example
/* Generate a random number ranging from 1 to 10. This example and execution result can be referenced with rand */
# Include <time. h>
# Include <stdlib. h>
Main ()
{
Int I, j;
Srand (int) time (0 ));
For (I = 0; I <10; I ++)
{
J = 1 + (int) (10.0 * rand ()/(RAND_MAX + 1.0 ));
Printf ("% d", j );
}
}
Execution: Compare with the rand example
5 8 8 8 10 2 10 8 9 9
2 9 7 4 10 3 2 10 8 7
Or:
Use "int x = rand () % 100;" to generate a random number between 0 and 100. This method is not or can be used. A better method is j = (int) (n * rand ()/(RAND_MAX + 1.0) generates a random number between 0 and n.
Int main (void)
{
Int I;
Time_t t;
Srand (unsigned) time (& t ));
Printf ("Ten r... the remaining full text>

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.