Sử dụng .Net Webservice trong Android

ngày 31-03-2016

Để làm được bài này thì các bạn nên xem qua trước bài tập Cách tạo WebserviceSử dụng .Net Webservice trong C#
 
Trong bài này, Tui muốn trình bày 4 ví dụ về cách tương tác từ Android tới .Net Webservice thông qua thư viện KSOAP API.
 
Các ví dụ này lần lượt sẽ là:
 
1) Cách lấy dữ liệu Primitive Data từ .net webservice xuống Android
 
2) Cách lấy dữ liệu Complex Data từ .net webservice xuống Android
 
3) Cách truyền Parameter primitive data từ Android tới .net web service
 
4) Cách truyền Object data từ Android tới .net web service
 
Thư viện KSOAP API các bạn tải ở đây (tạm thời tự nghiên cứu trước):
http://www.mediafire.com/download/kmznar1je4702ga/ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar
 
——————————————————————————
 
Tất cả 4 ví dụ này Tui sẽ sử dụng Service Description của
http://testdrthanh.somee.com/mywebservice.asmx?WSDL ở bài tập trước. Khi bạn mở với Service description thì nó cung cấp cho bạn đầy đủ thông tin như hình Tui chụp dưới đây:
 
 
NameSpace và tên hàm là rất quan trọng để dựa vào nó ta truy xuất dữ liệu, nên sai namespace hay method thì chắc chắn không thể truy suất.
 
Sau đây tui hướng dẫn các bạn những ví dụ ở trên
 
Các bài phải :
 
<uses-permission android:name=”android.permission.INTERNET” />
 
1) Cách lấy dữ liệu Primitive Data từ .net webservice xuống Android
 
– Bạn tạo một Project Android giống như hình Tui chụp dưới này:
 
 
Bạn chú ý là Tui đánh thứ tự từ 1, 2, 3, 4 là có ý đồ kỹ thuật. Bạn phải sắp xếp như vậy thì chương trình mới sử dụng đúng thư viện và có thể truy suất webservice, nếu đặt sai có thể nó báo lỗi không thể thực thi ứng dụng.
 
Mặc định khi bạn tạo Project thì nó sẽ không đúng thứ tự như vậy đâu, bạn phải tự làm lại thứ tự, cách đổi thứ tự như thế nào Tui sẽ nói rõ cho bạn.
 
Tiếp tới là bạn phải tham chiếu tới thự Viện KSOAP API mà tui khoanh màu đỏ, bạn lưu nó ở đâu thì bạn tham chiếu tới cho đúng, hoặc bạn có thể nhét nó vào thư viện libs. (bấm chuột phải vào Project / chọn Build Path/ chọn Add External Archives –> chọn đúng thư viện KSOAP API để add vào ứng dụng)
 
– Cách đổi thứ tự tham chiếu như sau:
 
Bấm chuột phải vào Project của bạn/ chọn Build Path/Configure build path…:
 
 
Cửa sổ mới hiển thị lên/chọn tab Order and export:
 
 
Ta sắp xếp như màn hình trên, để di chuyển thì dùng các nút : Up,down, top, bottom.
 
Bạn chú ý là phải đảm bảo rằng tất cả các mục trong này được CHECKED rồi mới bấm nút OK.
 
– Sau đây là giao diện chính (rất đơn giản) của project này như sau:
 
 
– Nút “Get Catalog count” sẽ triệu gọi Service và trả về có bao nhiêu Danh mục trong Cơ sở dữ liệu.
 
– Cấu trúc XML của giao diện:
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity" >
 
<TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Number Of Catalog:" />
 
<TextView
 android:id="@+id/txtcount"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="#008040"
 android:gravity="center"
 android:textColor="#FFFFFF"
 android:textSize="30sp" />
 
<Button
 android:id="@+id/btncount"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Get Catalog Count" />
 
</LinearLayout>
 
– Ta tiến hành xử lý coding trong MainActivity.java như sau:
 
package tranduythanh.com;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 TextView txtcount;
 Button btncount;
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 //thiết lập Permit để kết nối internet
 StrictMode.ThreadPolicy policy = new
 StrictMode.ThreadPolicy.Builder()
 .permitAll().build();
 StrictMode.setThreadPolicy(policy);
 
 txtcount=(TextView) findViewById(R.id.txtcount);
 btncount=(Button) findViewById(R.id.btncount);
 btncount.setOnClickListener(new
 View.OnClickListener() {
 public void onClick(View arg0) {
 doCount();
 }
 });
 }
 public void doCount(){
 try{
 //khai báo namespace trong Webservice
 final String NAMESPACE="http://tranduythanh.com/";
 //hàm cần truy suất
 final String METHOD_NAME="CountCatalog";
 final String SOAP_ACTION=NAMESPACE+METHOD_NAME;
 //service description
 final String URL="http://testdrthanh.somee.com/mywebservice.asmx?WSDL";
 //khai báo đối tượng SoapOBject
 SoapObject request=new SoapObject(NAMESPACE, METHOD_NAME);
 //thiết lập version
 SoapSerializationEnvelope envelope=
 new SoapSerializationEnvelope(SoapEnvelope.VER11);
 envelope.dotNet=true;
 //thiết lập output
 envelope.setOutputSoapObject(request);
 //tạo đối tượng HttpTransportSE
 HttpTransportSE androidHttpTransport=
 new HttpTransportSE(URL);
 //tiến hành triệu gọi Service
 androidHttpTransport.call(SOAP_ACTION, envelope);
 //lấy kết quả trả về SoapPrimitive, vì hàm CountCatalog chỉ trả về kiểu int (primitive data)
 SoapPrimitive response=(SoapPrimitive) envelope.getResponse();
 //hiển thị kết quả lên giao diện
 txtcount.setText(response.toString());
 }
 catch(Exception e) {
 e.printStackTrace();
 }
 }
}//end MainActivity
 
– Bạn quan sát dòng lệnh:
 
StrictMode.ThreadPolicy policy = new
 StrictMode.ThreadPolicy.Builder()
 .permitAll().build();
 StrictMode.setThreadPolicy(policy);
 
Dòng lệnh trên là cho phép ứng dụng kết nối tới internet, nhưng chú ý cách làm này là không TỐT, phải sửa lại. Từ Android 4.0 nó yêu cầu khi kết nối internet phải viết trong Tiểu Trình (dùng đa tiến trình, các bạn xem lại các ví dụ trước). Còn viết như bên trên TUI viết thì rất dở, nó làm Đơ Ứng Dụng vì phải mất Time Request, chỉ là giải pháp tình huống để các bạn dễ hiểu thôi.
 
Bạn nên xóa dòng lệnh bên trên đi, đưa hàm doCount() vào một tiểu trình (bạn dùng Handler class hoặc AsyncTask class), cách làm đa tiến trình Tui đã hướng dẫn rất kỹ lưỡng ở những bài trước, bài này các bạn tự làm (nếu không làm được thì chưa đạt).
 
Bạn tải source code ở đây (nhớ khi down về thì đổi lại tham chiếu tới thư viện KSOAP), bạn nên nhét nó vào thư mục Libs để chép tới nơi khác không phải tham chiếu lại:
 
 
Bạn phải chú ý làm nhiều lần để cho hiểu rõ vấn đề.
 
2) Cách lấy dữ liệu Complex Data từ .net webservice xuống Android
 
– Ở phần 1 Bạn đã biết cách truy suất webservice và trả về dữ liệu Primivite data, trong bài này Tui hướng dẫn các bạn lấy dữ liệu về dạng Complex Data.
 
– Cách cấu hình tham chiếu thư viện, đổi thứ tự tham chiếu … thì ở mục 1 tui đã nói, mục này Tui đi thẳng vào ứng dụng:
 
– Tui muốn tạo 1 Ứng dụng cho phép triệu gọi danh sách Danh Mục Sản phẩm từ webservice với giao diện vô cùng đơn giản như sau (bạn tạo ứng dụng tên là LearnWebservice_complex_data):
 
 
– Ứng dụng trên sẽ triệu gọi hàm : getListCatalog.
 
– Nó khác biệt là nó trả về danh sách đối tượng Danh Mục, làm thế nào để ta lấy được danh sách đối tượng nafy???
 
– Sau đây là XML Layout của ứng dụng:
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity" >
 
<Button
 android:id="@+id/btnlistcatalog"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Get List Catalog" />
 
<ListView
 android:id="@+id/lvcatalog"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>
 
</LinearLayout>
 
– Source code Xử lý trong MainActivity như sau:
 
package tranduythanh.com;
 
import java.util.ArrayList;
 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
 
public class MainActivity extends Activity {
 Button btngetlist;
 ListView lvcatalog;
 final String URL="http://testdrthanh.somee.com/mywebservice.asmx?WSDL";
 ArrayList<String> arrCate=new ArrayList<String>();
 ArrayAdapter<String>adapter=null;
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 StrictMode.ThreadPolicy policy = new
 StrictMode.ThreadPolicy.Builder()
 .permitAll().build();
 StrictMode.setThreadPolicy(policy);
 lvcatalog=(ListView) findViewById(R.id.lvcatalog);
 btngetlist=(Button) findViewById(R.id.btnlistcatalog);
 btngetlist.setOnClickListener(new View.OnClickListener() {
 public void onClick(View arg0)
 {doGetList();}
 });
 adapter=new ArrayAdapter<String>
 (this, android.R.layout.simple_list_item_1, arrCate);
 lvcatalog.setAdapter(adapter);
 }
 public void doGetList() {
 try{final String NAMESPACE="http://tranduythanh.com/";
 final String METHOD_NAME="getListCatalog";
 final String SOAP_ACTION=NAMESPACE+METHOD_NAME;
 SoapObject request=new SoapObject(NAMESPACE, METHOD_NAME);
 SoapSerializationEnvelope envelope=
 new SoapSerializationEnvelope(SoapEnvelope.VER11);
 envelope.dotNet=true;
 envelope.setOutputSoapObject(request);
 //Nếu truyền số thực trên mạng bắt buộc phải đăng ký MarshalFloat
 //không có nó thì bị báo lỗi
 MarshalFloat marshal=new MarshalFloat();
 marshal.register(envelope);
 
 HttpTransportSE androidHttpTransport=
 new HttpTransportSE(URL);
 androidHttpTransport.call(SOAP_ACTION, envelope);
 //Get Array Catalog into soapArray
 SoapObject soapArray=(SoapObject) envelope.getResponse();
 arrCate.clear();
 //soapArray.getPropertyCount() return number of
 //element in soapArray
 //vòng lặp duyệt qua từng dòng dữ liệu
 for(int i=0; i<soapArray.getPropertyCount(); i++)
 {
 //(SoapObject) soapArray.getProperty(i) get item at position i
 SoapObject soapItem =(SoapObject) soapArray.getProperty(i);
 //soapItem.getProperty("CateId") get value of CateId property
 //phải mapp đúng tên cột:
 String cateId=soapItem.getProperty("CateId").toString();
 String cateName=soapItem.getProperty("CateName").toString();
 //đẩy vào array
 arrCate.add(cateId+" - "+cateName);
 }
 //xác nhận cập nhật giao diện
 adapter.notifyDataSetChanged();
 }
 catch(Exception e){}}
}
 
Như vậy bạn chú ý có sự khác biệt trong Vòng lặp duyệt để lấy thông tin từng dòng đối tượng, bạn chú ý ngẫm nghĩ để tự áp dụng cho các bài toán khác (lấy danh sách sản phẩm, lấy danh sách sản phẩm theo danh mục ….)
 
 
Chú ý phải làm lại nhiều lần, nhất là Tui đảm bảo các bạn còn Quáng Gà với vòng lặp lấy dữ liệu ở trên.
 
3) Cách truyền Parameter primitive data từ Android tới .net web service
 
– Hai phần trên các bạn đã biết cách lấy dữ liệu primitive data và complex data từ Server về client, phần 3 này các bạn sẽ được học cách thức truyền dữ liệu từ client lên server thông qua Webservice như thế nào.
 
– Giao diện của bài tập 3 như sau:
 
 
– Mô tả sương sương như sau: Màn hình chính cho phép hiển thị danh mục, mỗi lần nhấn vào danh mục nào đó thì hiển thị danh sách sản phẩm của danh mục này. Ở đây ta dùng hàm getListProductByCatalogId của webservice để hiển thị danh sách sản phẩm theo danh mục.
 
- Bạn tạo Project như dưới đây:
 
 
– Vậy chương trình có 2 Activity, một số class: Product, Cate…
 
– Layout “activity_main.xml”:
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity" >
 
<Button
 android:id="@+id/btnlistcatalog"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Get List Catalog" />
 
<ListView
 android:id="@+id/lvcatalog"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>
 
</LinearLayout>
 
– Layout “activity_list_product_by_catalog.xml”:
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".ListProductByCatalogActivity" >
 <ListView
 android:id="@+id/lvproduct"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>
 
</LinearLayout>
 
– Lớp Product:
 
package tranduythanh.com;
 
public class Product {
 private String productId;
 private String productName;
 private int quantity;
 private double unitPrice;
 private double totalMoney;
 public String getProductId() {
 return productId;
 }
 public void setProductId(String productId) {
 this.productId = productId;
 }
 public String getProductName() {
 return productName;
 }
 public void setProductName(String productName) {
 this.productName = productName;
 }
 public int getQuantity() {
 return quantity;
 }
 public void setQuantity(int quantity) {
 this.quantity = quantity;
 }
 public double getUnitPrice() {
 return unitPrice;
 }
 public void setUnitPrice(double unitPrice) {
 this.unitPrice = unitPrice;
 }
 public double getTotalMoney() {
 return totalMoney;
 }
 public void setTotalMoney(double totalMoney) {
 this.totalMoney = totalMoney;
 }
 public Product(String productId, String productName, int quantity,
 double unitPrice, double totalMoney) {
 super();
 this.productId = productId;
 this.productName = productName;
 this.quantity = quantity;
 this.unitPrice = unitPrice;
 this.totalMoney = totalMoney;
 }
 @Override
 public String toString() {
 return this.productName+"-"+(this.totalMoney);
 }
 
}
 
– Lớp Cate:
 
package tranduythanh.com;
 
public class Cate {
 private String cateId;
 private String cateName;
 public String getCateId() {
 return cateId;
 }
 public void setCateId(String cateId) {
 this.cateId = cateId;
 }
 public String getCateName() {
 return cateName;
 }
 public void setCateName(String cateName) {
 this.cateName = cateName;
 }
 public Cate(String cateId, String cateName) {
 super();
 this.cateId = cateId;
 this.cateName = cateName;
 }
 @Override
 public String toString() {
 return this.cateId.trim()+" - "+this.cateName.trim();
 }
 
}
 
– Lớp MainActivity:
 
package tranduythanh.com;
 
import java.util.ArrayList;
 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 Button btngetlist;
 ListView lvcatalog;
 final String URL="http://testdrthanh.somee.com/mywebservice.asmx?WSDL";
 ArrayList<Cate> arrCate=new ArrayList<Cate>();
 ArrayAdapter<Cate>adapter=null;
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 StrictMode.ThreadPolicy policy = new
 StrictMode.ThreadPolicy.Builder()
 .permitAll().build();
 StrictMode.setThreadPolicy(policy);
 lvcatalog=(ListView) findViewById(R.id.lvcatalog);
 btngetlist=(Button) findViewById(R.id.btnlistcatalog);
 btngetlist.setOnClickListener(new View.OnClickListener() {
 public void onClick(View arg0)
 {doGetList();}
 });
 adapter=new ArrayAdapter<Cate>
 (this, android.R.layout.simple_list_item_1, arrCate);
 lvcatalog.setAdapter(adapter);
 
 lvcatalog.setOnItemClickListener(new OnItemClickListener() {
 @Override
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
 long arg3) {
 //xử lý hiển thị danh sách sản phẩm theo danh mục
 Cate c=arrCate.get(arg2);
 Intent in=new Intent(MainActivity.this, ListProductByCatalogActivity.class);
 in.putExtra("cateid", c.getCateId());
 startActivity(in);
 }
 });
 }
 
 public void doGetList() {
 try{final String NAMESPACE="http://tranduythanh.com/";
 final String METHOD_NAME="getListCatalog";
 final String SOAP_ACTION=NAMESPACE+METHOD_NAME;
 SoapObject request=new SoapObject(NAMESPACE, METHOD_NAME);
 SoapSerializationEnvelope envelope=
 new SoapSerializationEnvelope(SoapEnvelope.VER11);
 envelope.dotNet=true;
 envelope.setOutputSoapObject(request);
 //Nếu truyền số thực trên mạng bắt buộc phải đăng ký MarshalFloat
 //không có nó thì bị báo lỗi
 MarshalFloat marshal=new MarshalFloat();
 marshal.register(envelope);
 
 HttpTransportSE androidHttpTransport=
 new HttpTransportSE(URL);
 androidHttpTransport.call(SOAP_ACTION, envelope);
 //Get Array Catalog into soapArray
 SoapObject soapArray=(SoapObject) envelope.getResponse();
 arrCate.clear();
 //soapArray.getPropertyCount() return number of
 //element in soapArray
 //vòng lặp duyệt qua từng dòng dữ liệu
 for(int i=0; i<soapArray.getPropertyCount(); i++)
 {
 //(SoapObject) soapArray.getProperty(i) get item at position i
 SoapObject soapItem =(SoapObject) soapArray.getProperty(i);
 //soapItem.getProperty("CateId") get value of CateId property
 //phải mapp đúng tên cột:
 String cateId=soapItem.getProperty("CateId").toString();
 String cateName=soapItem.getProperty("CateName").toString();
 //đẩy vào array
 Cate c=new Cate(cateId, cateName);
 arrCate.add(c);
 }
 //xác nhận cập nhật giao diện
 adapter.notifyDataSetChanged();
 }
 catch(Exception e)
 {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
 }
 }
}
 
– Lớp ListProductByCatalogActivity:
 
package tranduythanh.com;
 
import java.util.ArrayList;
 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
 
public class ListProductByCatalogActivity extends Activity {
 ListView lvproduct;
 final String URL="http://testdrthanh.somee.com/mywebservice.asmx?WSDL";
 ArrayList<Product> arrProduct=new ArrayList<Product>();
 ArrayAdapter<Product>adapter=null;
 String cateId="";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_list_product_by_catalog);
 
StrictMode.ThreadPolicy policy = new
 StrictMode.ThreadPolicy.Builder()
 .permitAll().build();
 StrictMode.setThreadPolicy(policy);
 lvproduct=(ListView) findViewById(R.id.lvproduct);
 
adapter=new ArrayAdapter<Product>
 (this, android.R.layout.simple_list_item_1, arrProduct);
 lvproduct.setAdapter(adapter);
 
 Intent in=getIntent();
 cateId= in.getStringExtra("cateid");
 }
 @Override
 protected void onResume() {
 // TODO Auto-generated method stub
 super.onResume();
 doGetListProduct();
 }
 public void doGetListProduct()
 {
 try{
 final String NAMESPACE="http://tranduythanh.com/";
 final String METHOD_NAME="getListProductByCatalogId";
 final String SOAP_ACTION=NAMESPACE+METHOD_NAME;
 SoapObject request=new SoapObject(NAMESPACE, METHOD_NAME);
 request.addProperty("id", cateId);
 SoapSerializationEnvelope envelope=
 new SoapSerializationEnvelope(SoapEnvelope.VER11);
 envelope.dotNet=true;
 envelope.setOutputSoapObject(request);
 MarshalFloat marshal=new MarshalFloat();
 marshal.register(envelope);
 HttpTransportSE androidHttpTransport=
 new HttpTransportSE(URL);
 androidHttpTransport.call(SOAP_ACTION, envelope);
 
 //Get Array Catalog into soapArray
 SoapObject soapArray=(SoapObject) envelope.getResponse();
 arrProduct.clear();
 //soapArray.getPropertyCount() return number of
 //element in soapArray
 //vòng lặp duyệt qua từng dòng dữ liệu
 for(int i=0; i<soapArray.getPropertyCount(); i++)
 {
 //(SoapObject) soapArray.getProperty(i) get item at position i
 SoapObject soapItem =(SoapObject) soapArray.getProperty(i);
 //phải map đúng tên cột:
 String productId=soapItem.getProperty("ProductId").toString();
 String productName=soapItem.getProperty("ProductName").toString();
 String squantity=soapItem.getProperty("Quantity").toString();
 String sunitPrice=soapItem.getProperty("UnitPrice").toString();
 String stotalMoney=soapItem.getProperty("TotalMoney").toString();
 int quantity=Integer.parseInt(squantity);
 double unitPrice=Double.parseDouble(sunitPrice);
 double totalMoney=Double.parseDouble(stotalMoney);
 //đẩy vào array
 Product p=new Product(productId, productName, quantity, unitPrice, totalMoney);
 arrProduct.add(p);
 }
 //xác nhận cập nhật giao diện
 adapter.notifyDataSetChanged();
 }
 catch(Exception e) {}
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.list_product_by_catalog, menu);
 return true;
 }
 
}
 
– Quan sát dòng 55-56 đó là cách truyền Primivte data từ Android lên Webservice.
 
– Ta nên để trong OnReSume để đảm bảo rằng mọi thứ được sẵn sàng. Trong này sẽ lọc toàn bộ sản phẩm theo danh mục.
 
 
Các bạn chú ý phải làm lại nhiều lần bài 3 này vì nó khó và hay!
 
4) Cách truyền Object data từ Android tới .net web service
 
– Đây là phần cuối cùng Tui muốn hướng dẫn các bạn cách truyền Object Data từ Client Android lên Server thông qua Webservice.
 
– Ở bài tập 4 này bạn bổ sung thêm 1 hàm InsertCatalog vào Webservice, với đối số truyền vào là đối tượng Catalog:
 
//10 - thêm 1 catalog vào CSDL
 [WebMethod]
 public int insertCatalog(Catalog cate)
 {
 try
 {
 cate.Products.Clear();
 db.Catalogs.InsertOnSubmit(cate);
 db.SubmitChanges();
 }
 catch
 {
 return -1;
 }
 return 1;
 }
 
– Tui có giao diện đơn giản để demo cho phần này như sau:
 
 
– Khi nhấn nút “Show List Catalog”: Chương trình sẽ triệu gọi Webservice để hiển thị danh mục sản phẩm vào ListView bên dưới.
 
– Khi nhấn nút “Insert Cate”: Chương trình sẽ truyền đối tượng Catalog từ client lên Server thông qua Webservice. Ở đây Tui dùng cách truyền Properties cho tiện. Bạn chú ý phải quan sát kỹ Service Description của nó để truyền cho đúng Parameter:
 
 
– Tương tự như cho các hàm mà có truyền tham số khác cũng vậy, phải đặt đúng tên trong Service Descripton.
 
– Ta có XML Layout của ứng dụng như sau:
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity" >
 
<TextView
 android:id="@+id/textView2"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="#FFFF80"
 android:text="Input Catalog:"
 android:textSize="20sp" />
 
<TableLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 
<TableRow
 android:id="@+id/tableRow1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" >
 
<TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="#F0E7B3"
 android:text="Cate Id:" />
 
<EditText
 android:id="@+id/editcateid"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:ems="10"
 android:inputType="text" >
 
<requestFocus />
 </EditText>
 </TableRow>
 
<TableRow
 android:id="@+id/tableRow2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" >
 
<TextView
 android:id="@+id/textView2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="#F0E7B3"
 android:text="Cate Name:" />
 
<EditText
 android:id="@+id/editcatename"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:ems="10"
 android:inputType="text" />
 </TableRow>
 
<TableRow
 android:id="@+id/tableRow4"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" >
 
<Button
 android:id="@+id/btninsertcate"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_column="1"
 android:text="Insert Cate" />
 </TableRow>
 </TableLayout>
 
<TextView
 android:id="@+id/textView3"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="#FF80FF"
 android:text="Show List Catalog" />
 
<Button
 android:id="@+id/btnshowlist"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Show List Catalog" />
 
<ListView
 android:id="@+id/lvcatalog"
 android:layout_width="match_parent"
 android:layout_height="fill_parent" >
 </ListView>
 
</LinearLayout>
 
– Xử lý coding cho MainActivity như sau:
 
package tranduythanh.com;
 
import java.util.ArrayList;
 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.os.Bundle;
import android.os.StrictMode;
import android.renderscript.Mesh.Primitive;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
 
public class MainActivity extends Activity
 implements OnClickListener{
 EditText txtcateid,txtcatename;
 Button btninsertcate,btnlistcate;
 ListView lvlistcatalog;
 final String NAMESPACE="http://tranduythanh.com/";
 final String URL="http://testdrthanh.somee.com/mywebservice.asmx?WSDL";
 ArrayList<String> arrCate=new ArrayList<String>();
 ArrayAdapter<String>adapter=null;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
StrictMode.ThreadPolicy policy = new
 StrictMode.ThreadPolicy.Builder()
 .permitAll().build();
 StrictMode.setThreadPolicy(policy);
 
txtcateid=(EditText) findViewById(R.id.editcateid);
 txtcatename=(EditText) findViewById(R.id.editcatename);
 btninsertcate=(Button) findViewById(R.id.btninsertcate);
 btnlistcate=(Button) findViewById(R.id.btnshowlist);
 btninsertcate.setOnClickListener(this);
 btnlistcate.setOnClickListener(this);
 lvlistcatalog=(ListView) findViewById(R.id.lvcatalog);
 
adapter=new ArrayAdapter<String>
 (this, android.R.layout.simple_list_item_1, arrCate);
 lvlistcatalog.setAdapter(adapter);
 }
 
@Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.activity_main, menu);
 return true;
 }
 
@Override
 public void onClick(View v) {
 if(v==btnlistcate)
 {
 showlistcate();
 }
 else if(v==btninsertcate)
 {
 insertcate1();
 }
 }
 public void insertcate1()
 {
 try
 {
 final String METHOD_NAME="insertCatalog";
 final String SOAP_ACTION=NAMESPACE+METHOD_NAME;
 
 SoapObject request=new SoapObject
 (NAMESPACE, METHOD_NAME);
 //tạo đối tượng SoapObject với tên cate như parameter trong service description
 SoapObject newCate=new
 SoapObject(NAMESPACE, "cate");
 //truyền giá trị cho các đối số (properties) như service desctiption
 newCate.addProperty("CateId",
 txtcateid.getText()+"");
 
 newCate.addProperty("CateName",
 txtcatename.getText()+"");
 request.addSoapObject(newCate);
 
 SoapSerializationEnvelope envelope=
 new SoapSerializationEnvelope(SoapEnvelope.VER11);
 envelope.dotNet=true;
 envelope.setOutputSoapObject(request);
 
 HttpTransportSE androidHttpTransport=
 new HttpTransportSE(URL);
 androidHttpTransport.call(SOAP_ACTION, envelope);
 //vì hàm insertCatalog trả về kiểu int
 SoapPrimitive soapPrimitive= (SoapPrimitive)
 envelope.getResponse();
 //chuyển về int để kiểm tra insert thành công hay thất bại
 int ret=Integer.parseInt(soapPrimitive.toString());
 
 String msg="Insert Cate Successful";
 if(ret<=0)
 msg="Insert Cate Failed";
 Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
 }
 catch(Exception e)
 {
 
}
 }//end insert cate
 public void showlistcate() {
 try
 {
 final String METHOD_NAME="getListCatalog";
 final String SOAP_ACTION=NAMESPACE+METHOD_NAME;
 SoapObject request=new SoapObject(NAMESPACE, METHOD_NAME);
 SoapSerializationEnvelope envelope=
 new SoapSerializationEnvelope(SoapEnvelope.VER11);
 envelope.dotNet=true;
 envelope.setOutputSoapObject(request);
 MarshalFloat marshal=new MarshalFloat();
 marshal.register(envelope);
 HttpTransportSE androidHttpTransport=
 new HttpTransportSE(URL);
 androidHttpTransport.call(SOAP_ACTION, envelope);
 //Get Array Catalog into soapArray
 SoapObject soapArray=(SoapObject) envelope.getResponse();
 arrCate.clear();
 //soapArray.getPropertyCount() return number of
 //element in soapArray
 for(int i=0; i<soapArray.getPropertyCount(); i++)
 {
 //(SoapObject) soapArray.getProperty(i) get item at position i
 SoapObject soapItem =(SoapObject) soapArray.getProperty(i);
 //soapItem.getProperty("CateId") get value of CateId property
 String cateId=soapItem.getProperty("CateId").toString();
 String cateName=soapItem.getProperty("CateName").toString();
 arrCate.add(cateId+" - "+cateName);
 }
 arrCate.add(soapArray.getPropertyCount()+" -- cate");
 adapter.notifyDataSetChanged();
 }
 catch(Exception e)
 {
 
}
 }
}
 
 
– Như vậy Tui đã hướng dẫn đầy đủ 4 trường hợp thường gặp phải khi các bạn lập trình Android với .Net Webservice. Các bạn cần chú tâm nghiên cứu, ngoài ra cần tự học thêm JSON (JavaScript Object Notation) cho đủ bộ.
 
– Chúc các bạn thành công!
 
Nguồn: Thầy Trần Duy Thanh - Giảng viên tại Trung Tâm Tin Học Đại học Khoa Học Tự Nhiên
 
Thông tin về khóa học Xây dựng và triển khai Web Service cho ứng dụng di động:
 
http://laptrinhdidong.csc.edu.vn/khoa-hoc/Trien-Khai-Web-Service
 
ai
Trung Tâm Tin Học
ai
Trung Tâm Tin Học
Chào mừng bạn đến với Trung Tâm Tin Học.
Bạn đang cần hỗ trợ thông tin gì ạ? Hãy Chat ngay với chúng tôi nhé.