C # How programmers learn Android Development Series and call WebService
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
Params) {final String SOAP_ACTION = nameSpace + methodName; SoapObject soapObject = new SoapObject (nameSpace, methodName); if (params! = Null )&&(! Params. isEmpty () {Iterator
> It = params. entrySet (). iterator (); while (it. hasNext () {Map. Entry
E = (Map. Entry
) It. next (); soapObject. addProperty (e. getKey (), e. getValue () ;}} SoapSerializationEnvelope envelope = new SoapSerializationEnvelope (SoapEnvelope. VER11); envelope. bodyOut = soapObject; // compatible. 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 JSON string contains fields * @ return returns List
> Type list, Map
Structure corresponding to id: 1 */public static List
> ConvertJSON2List (String result, String name, String [] fields) {List
> List = new ArrayList
> (); Try {JSONArray array = new JSONObject (result ). getJSONArray (name); for (int I = 0; I <array. length (); I ++) {JSONObject object = (JSONObject) array. opt (I); Map
Map = new HashMap
(); 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 nameSpac E = 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
> 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. Through the Intent object, we will > Passed in to the new Activity. You must note 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 (); // get the passed List
> Object @ SuppressWarnings (unchecked) List
> List = (List
>) 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. required: List
> Structure list, that is, 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.