C # Programmer learns the call of Android Development series WebService

Source: Internet
Author: User
Tags wsdl

The first question I encountered while learning about Android development was how did the Android client interact with the server database? It was a big question I had when I first approached Android, and it was not until a few years ago that I suddenly thought WebService could do it. Let WebService act as a server-side role, complete with the server database operations, and the Android client just follow the WebService method parameters to call the line. At the time I did not blur the implementation of this solution, I think this problem is also a beginner Android friends will certainly think of the problem. So now let's get it done.

This program shows how to request a Web service to get the data provided by the server.

Because I am familiar with C #, I prefer to use my familiar techniques to build webservice projects. It's easy for us to create a Web service application with the VS tool (VS2008, and start with WCF to create a service application from VS2010, but it's also easy to create a webservice with 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", "[email protected]");            Dt. Rows.Add (2, "jinyingying", "[email protected]");            Dt. Rows.Add (3, "jinyingying", "[email protected]");            Dt. Rows.Add (4, "jinyingying", "[email protected]");            return util.createjsonparameters (DT);        }
The WebService method is simple, which is to assemble a DataTable data type and convert it to a JSON string using the Createjsonparameters method. The DataTable in this can be modified to read data from the database side to the DataTable object.

        public static string Createjsonparameters (DataTable dt) {StringBuilder jsonstring = new STRINGB            Uilder (); 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 I from the Internet casually find a method, compare soil, is directly splicing JSON string (no matter, this is not the focus of our concern).

The WebService side is ready to publish to IIS. The publishing method is the same as the Web site, if it is native, you can directly test the results returned by the WebService method, such as the following results:

There must be someone here asking, this is XML outside, and it's JSON, isn't it "Sibuxiang"? Yes, I'm doing this to make it clear that WebService is soap-based, and the data transfer format is XML, so it's natural to get an XML document here. If you want a pure JSON string, you can use the WCF framework in C # (you can specify that the client returns the JSON format) or a servlet in Java (just brush out the JSON text).

Okay, so we're going to do two things next:

1. Request this webservice to get this JSON string

2. Format this JSON string to display in Android

Let's start with an assistant class, which is the way I'm going to encapsulate the two operations myself.

/** * @author Gary.gu Helper Class */public final class Util {/** * @param nameSpace ws namespace * @param methodName ws Method Name * @param w The full pathname of the SDL ws WSDL * @param the parameters required by the method of the params WS * @return Soapobject object */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 ())) {Itera Tor<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. NET development of Web serviceenvelope.dotnet = true; Httptransportse 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 contained in field JSON String * @return return LIST&LT;MAP&LT;STR List of ing,object>> types,map<string,object> corresponds to "id": Structure of "1" */public static list<map<string, object> > convertjson2list (String result,string name, string[] fields) {list<map<string, object>> List = new Array List<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 that in C # to annotate methods, you can press 3 times "/", with the help of VS can be automatically generated. In Eclipse, you can enter "/**" on 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 = New button (L.getcontext ()); Button.settext ("Click on Native WebService"); L.addview (button); Setcontentview (L); Button.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {final String nameSpace = " http://tempuri.org/"; final string methodName =" Datatabletest "; final string wsdl =" http://10.77.137.119:8888/ Webservicetest/service1.asmx? WSDL ";//Call WebService return Soapobject object Soapobject soapobject = UTIL.CALLWS (nameSpace, methodname,wsdl, NULL); if ( Soapobject! = null) {//Get the value of the Datatabletestresult property of the Soapobject object string result = Soapobject.getproperty (" Datatabletestresult "). ToString (); Toast.maketext (testws.this, result, Toast.length_short). Show (); try {//To convert the JSON string to the structure of list list<map<string, object>> list = Util.convertjson2list (result, "result_list", new string[] {"id", "name", "EmaiL "});//The list is passed through Intent to the new activityintent newintent = Intent (Testws.this,gridviewtest.class); Bundle bundle = new bundle ();//list must be a Serializable type bundle.putserializable ("Key", (Serializable) list); Newintent.putextras (bundle);//Start a new activitystartactivity (newintent);} catch (Exception e) {e.printstacktrace ();}} else {System.out.println ("This is null ...");}});}}

Here are two points to note:

1. This activity does not load the layout file, but instead creates a button from the code, which is also a way to create a view.

2, through the intent object, we will list<map<string,object>> into the new activity, this intent between the value of the method needs attention.

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 ();//Get Incoming List<map<string,object>> object @suppresswarnings ("unchecked") list<map<string, object>> list = (list<map<string, object>>) bundle.getserializable ("key"); /Find GridView Object Grid = (GridView) Findviewbyid (R.ID.GRID01) by Findviewbyid method;//simpleadapter Adapter fills//1.context Current context, In this notation, or gridviewtest.this//2.data a list of Maps. Requirements are the list<map<string,object>> structure, that is, the data source//3.resource cloth Where does the local file//4.from come from, extracting which key//5.to from the data source list, that is, populating the controls in the layout file Simpleadapter adapter = new Simpleadapter (This, Lis T,r.layout.list_item, new string[] {"id", "name", "email"},new int[] {r.id.id, r.id.name, r.id.email});//will GridView and adapter Bind Grid.setadapter (adapter);}}
Get the list object passed in first, and then bind to the GridView by 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:o rientation= "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>
Androidmanifest.xml Full 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= "/> <uses-permission android:name=" Andro Id.permission.INTERNET "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launc She "android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity an Droid:name= ". Testws "android:label=" @string/app_name "> <intent-filter> <action Androi D:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/&gt            ; </intent-filter> </activity> <activity android:name= ". Gridviewtest "Android:label=" @String/app_name "> </activity> </application></manifest> 

Finally, the data obtained from the database server is shown on the emulator:




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.