轉自:http://blog.csdn.net/zhyl8157121/article/details/8169172
本文爲原創,如果轉載請註明出處 http://blog.csdn.net/zhyl8157121/article/details/8169172
其實之前發過一篇這樣的博文http://blog.csdn.net/zhyl8157121/article/details/7709552,但那個只是簡單記錄了一些自己的想法,並沒有想作爲教程來看,後來由於一些朋友想要源代碼,就附上了下載地址,但並沒有做什麼講解,從現在開始,準備做一份詳細的Android如何連接Sqlserver的教程.由於本人才疏學淺,如果有什麼不對的地方歡迎大家批評指正.
爲了避免再次被說標題黨,這裏先說明些事情:
第一,android沒法直接連接SQLServer,起碼我沒有發現方法,想想看,sqlserver安裝之後有多大,android程序是跑在手機上的,想讓程序直接訪問sqlserver,那手機要多大的內存?
第二,本文是通過一個“橋樑”——webservice來間接訪問SQLServer的,當然還有其他方法,感興趣的同學可以自行百度。
如果理解了上面兩點,好了咱們繼續。
教程會拿一個具體的例子來講,一步一步來,也許細節上還可以繼續加工,但大致的流程就是這樣的。
本教程有五個部分:
- 項目說明
- 開發環境部署
- 數據庫設計
- 服務器端程序設計
- 客戶端(android端)程序設計
項目說明
這個項目意在實現一個簡單的android連接Sqlserver的功能。
就做一個簡單的庫存管理功能,包括對倉庫內現有貨物的查看、貨物信息的增加&刪除。
開發環境的部署
今天主要講解第一個部分,開發環境的部署.
操作系統:Windows764bit 旗艦版
當然這個是什麼基本無所謂,只是我是在這上面開發的,不過家庭普通版的貌似不能配置IIS,就是咱們後面要使用的一個服務.
android端:eclipse + ADT集成開發環境
相信看到這個教程的基本都知道如何做這些了.如果真的是有哪位同學android開發環境沒有配置好而來看這篇教程,請先移步->www.google.com
服務器端:VisualStudio 2010 旗艦版
這個是用來寫website/webservice的,開發語言使用C# (即.net)
數據庫:SQLServer2008 R2
其實這個是什麼版本也無所謂吧,教程使用的都是比較基本的東西,所以版本的差異基本可以忽略。
IIS 7.5:正確配置並開啓IIS服務
如果想將website/webservice發佈出去就要開啓這個服務。但是如果僅僅是在本地進行測試就不需要配置,直接在VS中運行就可以。
其實我在開發的時候也只是配置IIS的時候遇到了一些問題,這裏給出IIS的配置方法.
http://wenku.baidu.com/view/95cf9fd9ad51f01dc281f1af.html這篇文庫給的還是很詳細的,我當初就是照着這個配置的。
數據庫設計
數據庫名稱:StockManage
表設計
表名稱:C
表說明:
列名 |
中文名稱 |
數據型態 |
必填 |
說明 |
Cno |
貨物編號 |
Int |
V |
主鍵,自增 |
Cname |
貨物名稱 |
String |
|
|
Cnum |
貨物數量 |
Int |
|
|
下圖是設計表的時候的截圖。
向表中輸入內容
吐槽一下:爲什麼這裏貓、狗、電話都有,甚至還有Surface?!這隻能說當時LZ在想這些……
服務器端程序設計(Webservice)
其實服務端可以寫成webservice也可以寫成website,前者只是提供一種服務,而後者是可以提供用戶界面等具體的頁面,後者也就是咱們平時所說的“網站”。
兩者的區別:
- Web Service 只提供程序和接口,不提供用戶界面
- Web Site 提供程序和接口,也提供用戶界面(網頁)
由於咱們只是需要一箇中介來訪問sqlserver,所以寫成webservice足夠了。
目標:寫一個Website訪問Sqlserver,獲取數據並轉換成xml格式,然後傳遞給android客戶端。
1. 新建一個Webservice工程
2. 視圖 -> 其它窗口 -> 服務器資源管理器
3. 右鍵數據連接 -> 添加連接
4. 選擇Microsoft Sqlserver
5. 如下圖所示選擇(可以點擊測試連接來檢測連接是否成功,然後點擊確定)
6. 數據庫的查看和編輯也可以在VS中進行了
7. 先查看一下數據庫屬性並記錄下連接屬性
8. 新建一個類DBOperation,代碼如下:
- using System;
- using System.Data;
- using System.Configuration;
- using System.Linq;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Xml.Linq;
- using System.Data.SqlClient;
- using System.Text.RegularExpressions;
- using System.Collections;
- using System.Collections.Generic;
- namespace StockManageWebservice
- {
- /// <summary>
- /// 一個操作數據庫的類,所有對SQLServer的操作都寫在這個類中,使用的時候實例化一個然後直接調用就可以
- /// </summary>
- public class DBOperation:IDisposable
- {
- public static SqlConnection sqlCon; //用於連接數據庫
- //將下面的引號之間的內容換成上面記錄下的屬性中的連接字符串
- private String ConServerStr = @"Data Source=BOTTLE-PC;Initial Catalog=StockManage;Integrated Security=True";
- //默認構造函數
- public DBOperation()
- {
- if (sqlCon == null)
- {
- sqlCon = new SqlConnection();
- sqlCon.ConnectionString = ConServerStr;
- sqlCon.Open();
- }
- }
- //關閉/銷燬函數,相當於Close()
- public void Dispose()
- {
- if (sqlCon != null)
- {
- sqlCon.Close();
- sqlCon = null;
- }
- }
- /// <summary>
- /// 獲取所有貨物的信息
- /// </summary>
- /// <returns>所有貨物信息</returns>
- public List<string> selectAllCargoInfor()
- {
- List<string> list = new List<string>();
- try
- {
- string sql = "select * from C";
- SqlCommand cmd = new SqlCommand(sql,sqlCon);
- SqlDataReader reader = cmd.ExecuteReader();
- while (reader.Read())
- {
- //將結果集信息添加到返回向量中
- list.Add(reader[0].ToString());
- list.Add(reader[1].ToString());
- list.Add(reader[2].ToString());
- }
- reader.Close();
- cmd.Dispose();
- }
- catch(Exception)
- {
- }
- return list;
- }
- /// <summary>
- /// 增加一條貨物信息
- /// </summary>
- /// <param name="Cname">貨物名稱</param>
- /// <param name="Cnum">貨物數量</param>
- public bool insertCargoInfo(string Cname, int Cnum)
- {
- try
- {
- string sql = "insert into C (Cname,Cnum) values ('" + Cname + "'," + Cnum + ")";
- SqlCommand cmd = new SqlCommand(sql, sqlCon);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- /// <summary>
- /// 刪除一條貨物信息
- /// </summary>
- /// <param name="Cno">貨物編號</param>
- public bool deleteCargoInfo(string Cno)
- {
- try
- {
- string sql = "delete from C where Cno=" + Cno;
- SqlCommand cmd = new SqlCommand(sql, sqlCon);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- }
- }
9. 修改Service1.asmx.cs代碼如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
- namespace StockManageWebservice
- {
- /// <summary>
- /// Service1 的摘要說明
- /// </summary>
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
- // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的註釋。
- // [System.Web.Script.Services.ScriptService]
- public class Service1 : System.Web.Services.WebService
- {
- DBOperation dbOperation = new DBOperation();
- [WebMethod]
- public string HelloWorld()
- {
- return "Hello World";
- }
- [WebMethod(Description = "獲取所有貨物的信息")]
- public string[] selectAllCargoInfor()
- {
- return dbOperation.selectAllCargoInfor().ToArray();
- }
- [WebMethod(Description = "增加一條貨物信息")]
- public bool insertCargoInfo(string Cname, int Cnum)
- {
- return dbOperation.insertCargoInfo(Cname, Cnum);
- }
- [WebMethod(Description = "刪除一條貨物信息")]
- public bool deleteCargoInfo(string Cno)
- {
- return dbOperation.deleteCargoInfo(Cno);
- }
- }
- }
10. 運行程序(F5),會自動打開一個瀏覽器,可以看到如下畫面:
11. 選擇相應的功能並傳遞參數可以實現調試從瀏覽器中調試程序:
下圖選擇的是增加一條貨物信息
12. 程序執行的結果:
13.另,記住這裏的端口名,後面android的程序中添入的端口號就是這個:
客戶端(android端)程序設計
程序代碼:
1.MainActivity
- package com.bottle.stockmanage;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import android.app.Activity;
- import android.app.Dialog;
- import android.os.Bundle;
- import android.view.Gravity;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.Window;
- import android.view.WindowManager;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- import android.widget.Toast;
- public class MainActivity extends Activity{
- private Button btn1;
- private Button btn2;
- private Button btn3;
- private ListView listView;
- private SimpleAdapter adapter;
- private DBUtil dbUtil;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btn1 = (Button) findViewById(R.id.btn_all);
- btn2 = (Button) findViewById(R.id.btn_add);
- btn3 = (Button) findViewById(R.id.btn_delete);
- listView = (ListView) findViewById(R.id.listView);
- dbUtil = new DBUtil();
- btn1.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- hideButton(true);
- setListView();
- }
- });
- btn2.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- hideButton(true);
- setAddDialog();
- }
- });
- btn3.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- hideButton(true);
- setDeleteDialog();
- }
- });
- }
- /**
- * 設置彈出刪除對話框
- */
- private void setDeleteDialog() {
- final Dialog dialog = new Dialog(MainActivity.this);
- dialog.setContentView(R.layout.dialog_delete);
- dialog.setTitle("輸入想要刪除的貨物的編號");
- Window dialogWindow = dialog.getWindow();
- WindowManager.LayoutParams lp = dialogWindow.getAttributes();
- dialogWindow.setGravity(Gravity.CENTER);
- dialogWindow.setAttributes(lp);
- final EditText cNoEditText = (EditText) dialog.findViewById(R.id.editText1);
- Button btnConfirm = (Button) dialog.findViewById(R.id.button1);
- Button btnCancel = (Button) dialog.findViewById(R.id.button2);
- btnConfirm.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- dbUtil.deleteCargoInfo(cNoEditText.getText().toString());
- dialog.dismiss();
- hideButton(false);
- Toast.makeText(MainActivity.this, "成功刪除數據", Toast.LENGTH_SHORT).show();
- }
- });
- btnCancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- hideButton(false);
- }
- });
- dialog.show();
- }
- /**
- * 設置彈出添加對話框
- */
- private void setAddDialog() {
- final Dialog dialog = new Dialog(MainActivity.this);
- dialog.setContentView(R.layout.dialog_add);
- dialog.setTitle("輸入添加的貨物的信息");
- Window dialogWindow = dialog.getWindow();
- WindowManager.LayoutParams lp = dialogWindow.getAttributes();
- dialogWindow.setGravity(Gravity.CENTER);
- dialogWindow.setAttributes(lp);
- final EditText cNameEditText = (EditText) dialog.findViewById(R.id.editText1);
- final EditText cNumEditText = (EditText) dialog.findViewById(R.id.editText2);
- Button btnConfirm = (Button) dialog.findViewById(R.id.button1);
- Button btnCancel = (Button) dialog.findViewById(R.id.button2);
- btnConfirm.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- dbUtil.insertCargoInfo(cNameEditText.getText().toString(), cNumEditText.getText().toString());
- dialog.dismiss();
- hideButton(false);
- Toast.makeText(MainActivity.this, "成功添加數據", Toast.LENGTH_SHORT).show();
- }
- });
- btnCancel.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.dismiss();
- hideButton(false);
- }
- });
- dialog.show();
- }
- /**
- * 設置listView
- */
- private void setListView() {
- listView.setVisibility(View.VISIBLE);
- List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
- list = dbUtil.getAllInfo();
- adapter = new SimpleAdapter(
- MainActivity.this,
- list,
- R.layout.adapter_item,
- new String[] { "Cno", "Cname", "Cnum" },
- new int[] { R.id.txt_Cno, R.id.txt_Cname, R.id.txt_Cnum });
- listView.setAdapter(adapter);
- }
- /**
- * 設置button的可見性
- */
- private void hideButton(boolean result) {
- if (result) {
- btn1.setVisibility(View.GONE);
- btn2.setVisibility(View.GONE);
- btn3.setVisibility(View.GONE);
- } else {
- btn1.setVisibility(View.VISIBLE);
- btn2.setVisibility(View.VISIBLE);
- btn3.setVisibility(View.VISIBLE);
- }
- }
- /**
- * 返回按鈕的重寫
- */
- @Override
- public void onBackPressed()
- {
- if (listView.getVisibility() == View.VISIBLE) {
- listView.setVisibility(View.GONE);
- hideButton(false);
- }else {
- MainActivity.this.finish();
- }
- }
- }
2.HttpConnSoap
(改類已經過時,更多請參照
http://blog.csdn.net/zhyl8157121/article/details/8709048)
- package com.bottle.stockmanage;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.ArrayList;
- public class HttpConnSoap {
- public ArrayList<String> GetWebServre(String methodName, ArrayList<String> Parameters, ArrayList<String> ParValues) {
- ArrayList<String> Values = new ArrayList<String>();
- //ServerUrl是指webservice的url
- //10.0.2.2是讓android模擬器訪問本地(PC)服務器,不能寫成127.0.0.1
- //11125是指端口號,即掛載到IIS上的時候開啓的端口
- //Service1.asmx是指提供服務的頁面
- String ServerUrl = "http://10.0.2.2:11125/Service1.asmx";
- //String soapAction="http://tempuri.org/LongUserId1";
- String soapAction = "http://tempuri.org/" + methodName;
- //String data = "";
- String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
- + "<soap:Body />";
- String tps, vps, ts;
- String mreakString = "";
- mreakString = "<" + methodName + " xmlns=\"http://tempuri.org/\">";
- for (int i = 0; i < Parameters.size(); i++) {
- tps = Parameters.get(i).toString();
- //設置該方法的參數爲.net webService中的參數名稱
- vps = ParValues.get(i).toString();
- ts = "<" + tps + ">" + vps + "</" + tps + ">";
- mreakString = mreakString + ts;
- }
- mreakString = mreakString + "</" + methodName + ">";
- /*
- +"<HelloWorld xmlns=\"http://tempuri.org/\">"
- +"<x>string11661</x>"
- +"<SF1>string111</SF1>"
- + "</HelloWorld>"
- */
- String soap2 = "</soap:Envelope>";
- String requestData = soap + mreakString + soap2;
- //System.out.println(requestData);
- try {
- URL url = new URL(ServerUrl);
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- byte[] bytes = requestData.getBytes("utf-8");
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
- con.setConnectTimeout(6000);// 設置超時時間
- con.setRequestMethod("POST");
- con.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
- con.setRequestProperty("SOAPAction", soapAction);
- con.setRequestProperty("Content-Length", "" + bytes.length);
- OutputStream outStream = con.getOutputStream();
- outStream.write(bytes);
- outStream.flush();
- outStream.close();
- InputStream inStream = con.getInputStream();
- //data=parser(inStream);
- //System.out.print("11");
- Values = inputStreamtovaluelist(inStream, methodName);
- //System.out.println(Values.size());
- return Values;
- } catch (Exception e) {
- System.out.print("2221");
- return null;
- }
- }
- public ArrayList<String> inputStreamtovaluelist(InputStream in, String MonthsName) throws IOException {
- StringBuffer out = new StringBuffer();
- String s1 = "";
- byte[] b = new byte[4096];
- ArrayList<String> Values = new ArrayList<String>();
- Values.clear();
- for (int n; (n = in.read(b)) != -1;) {
- s1 = new String(b, 0, n);
- out.append(s1);
- }
- System.out.println(out);
- String[] s13 = s1.split("><");
- String ifString = MonthsName + "Result";
- String TS = "";
- String vs = "";
- Boolean getValueBoolean = false;
- for (int i = 0; i < s13.length; i++) {
- TS = s13[i];
- System.out.println(TS);
- int j, k, l;
- j = TS.indexOf(ifString);
- k = TS.lastIndexOf(ifString);
- if (j >= 0) {
- System.out.println(j);
- if (getValueBoolean == false) {
- getValueBoolean = true;
- } else {
- }
- if ((j >= 0) && (k > j)) {
- System.out.println("FFF" + TS.lastIndexOf("/" + ifString));
- //System.out.println(TS);
- l = ifString.length() + 1;
- vs = TS.substring(j + l, k - 2);
- //System.out.println("fff"+vs);
- Values.add(vs);
- System.out.println("退出" + vs);
- getValueBoolean = false;
- return Values;
- }
- }
- if (TS.lastIndexOf("/" + ifString) >= 0) {
- getValueBoolean = false;
- return Values;
- }
- if ((getValueBoolean) && (TS.lastIndexOf("/" + ifString) < 0) && (j < 0)) {
- k = TS.length();
- //System.out.println(TS);
- vs = TS.substring(7, k - 8);
- //System.out.println("f"+vs);
- Values.add(vs);
- }
- }
- return Values;
- }
- }
3.DBUtil
- package com.bottle.stockmanage;
- import java.sql.Connection;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- public class DBUtil {
- private ArrayList<String> arrayList = new ArrayList<String>();
- private ArrayList<String> brrayList = new ArrayList<String>();
- private ArrayList<String> crrayList = new ArrayList<String>();
- private HttpConnSoap Soap = new HttpConnSoap();
- public static Connection getConnection() {
- Connection con = null;
- try {
- //Class.forName("org.gjt.mm.mysql.Driver");
- //con=DriverManager.getConnection("jdbc:mysql://192.168.0.106:3306/test?useUnicode=true&characterEncoding=UTF-8","root","initial");
- } catch (Exception e) {
- //e.printStackTrace();
- }
- return con;
- }
- /**
- * 獲取所有貨物的信息
- *
- * @return
- */
- public List<HashMap<String, String>> getAllInfo() {
- List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
- arrayList.clear();
- brrayList.clear();
- crrayList.clear();
- crrayList = Soap.GetWebServre("selectAllCargoInfor", arrayList, brrayList);
- HashMap<String, String> tempHash = new HashMap<String, String>();
- tempHash.put("Cno", "Cno");
- tempHash.put("Cname", "Cname");
- tempHash.put("Cnum", "Cnum");
- list.add(tempHash);
- for (int j = 0; j < crrayList.size(); j += 3) {
- HashMap<String, String> hashMap = new HashMap<String, String>();
- hashMap.put("Cno", crrayList.get(j));
- hashMap.put("Cname", crrayList.get(j + 1));
- hashMap.put("Cnum", crrayList.get(j + 2));
- list.add(hashMap);
- }
- return list;
- }
- /**
- * 增加一條貨物信息
- *
- * @return
- */
- public void insertCargoInfo(String Cname, String Cnum) {
- arrayList.clear();
- brrayList.clear();
- arrayList.add("Cname");
- arrayList.add("Cnum");
- brrayList.add(Cname);
- brrayList.add(Cnum);
- Soap.GetWebServre("insertCargoInfo", arrayList, brrayList);
- }
- /**
- * 刪除一條貨物信息
- *
- * @return
- */
- public void deleteCargoInfo(String Cno) {
- arrayList.clear();
- brrayList.clear();
- arrayList.add("Cno");
- brrayList.add(Cno);
- Soap.GetWebServre("deleteCargoInfo", arrayList, brrayList);
- }
- }
4.activity_main.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- <ListView
- android:id="@+id/listView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:visibility="gone" >
- </ListView>
- <Button
- android:id="@+id/btn_all"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_above="@+id/btn_add"
- android:layout_alignLeft="@+id/btn_add"
- android:layout_marginBottom="10dip"
- android:text="@string/btn1" />
- <Button
- android:id="@+id/btn_add"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:text="@string/btn2" />
- <Button
- android:id="@+id/btn_delete"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/btn_add"
- android:layout_below="@+id/btn_add"
- android:layout_marginTop="10dip"
- android:text="@string/btn3" />
- </RelativeLayout>
5.adapter_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:descendantFocusability="blocksDescendants"
- android:gravity="center" >
- <TableRow
- android:id="@+id/classroom_detail_item_tableRow"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:gravity="center" >
- <TextView
- android:id="@+id/txt_Cno"
- android:layout_width="80dp"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:height="40dp"
- android:textSize="14sp" >
- </TextView>
- <TextView
- android:id="@+id/txt_Cname"
- android:layout_width="80dp"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:height="40dp"
- android:textSize="14sp" >
- </TextView>
- <TextView
- android:id="@+id/txt_Cnum"
- android:layout_width="80dp"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:height="40dp"
- android:textSize="14sp" >
- </TextView>
- </TableRow>
- </TableLayout>
6.dialog_add.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <EditText
- android:id="@+id/editText1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="@string/add_hint1" >
- <requestFocus />
- </EditText>
- <EditText
- android:id="@+id/editText2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="@string/add_hint2"
- android:inputType="number" />
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
- <Button
- android:id="@+id/button1"
- android:layout_width="100dip"
- android:layout_height="wrap_content"
- android:layout_marginLeft="20dip"
- android:text="@string/confirm" />
- <Button
- android:id="@+id/button2"
- android:layout_width="100dip"
- android:layout_height="wrap_content"
- android:layout_marginLeft="40dip"
- android:text="@string/cancel" />
- </LinearLayout>
- </LinearLayout>
7.dialog_delete.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <EditText
- android:id="@+id/editText1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:ems="10"
- android:hint="@string/delete_hint" >
- <requestFocus />
- </EditText>
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
- <Button
- android:id="@+id/button1"
- android:layout_width="100dip"
- android:layout_height="wrap_content"
- android:layout_marginLeft="20dip"
- android:text="@string/confirm" />
- <Button
- android:id="@+id/button2"
- android:layout_width="100dip"
- android:layout_height="wrap_content"
- android:layout_marginLeft="40dip"
- android:text="@string/cancel" />
- </LinearLayout>
- </LinearLayout>
8.strings.xml
- <resources>
- <string name="app_name">StockManagement</string>
- <string name="menu_settings">Settings</string>
- <string name="title_activity_main">MainActivity</string>
- <string name="btn1">查看所有貨物信息</string>
- <string name="btn2">增加一條貨物信息</string>
- <string name="btn3">刪除一條貨物信息</string>
- <string name="add_hint1">輸入添加的貨物的名稱</string>
- <string name="add_hint2">輸入貨物的數量</string>
- <string name="confirm">確定</string>
- <string name="cancel">取消</string>
- <string name="delete_hint">輸入刪除的貨物的編號</string>
- </resources>
9.Manifest.xml
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.bottle.stockmanage"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="7"
- android:targetSdkVersion="15" />
- <uses-permission android:name="android.permission.INTERNET" />
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@android:style/Theme.NoTitleBar" >
- <activity
- android:name=".MainActivity"
- android:label="@string/title_activity_main"
- android:screenOrientation="portrait" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
運行程序的效果如下圖所示:
再說一下IIS,如果只是在本地進行測試等操作,是不需要使用到IIS的,但是如果想發佈出去,就要配置一下IIS。
好啦,基本就是這樣了。程序不是完善的,但大概的思路就是這樣,用到的技術也大概就是這幾樣,但是每一樣拿出來都夠學一陣的了。
--->2012.12.02 增加內容
附上本文demo的CSDN下載地址
http://download.csdn.net/detail/zhyl8157121/4836107
--->2013.01.08 增加內容
解釋一下android端如何和webservice通信的。(如何修改實例程序)
具體的更深層的東西已經在HttpSoap中封裝好了,所以大家使用的時候可以直接用這個類就可以了。(我也不懂是怎麼實現的……)
android調用的方法就是如DBUtil中那樣,比如
其中arrayList中和brrayList中分別存放對應的webservice中“selectAllCargoInfor”方法的參數名和參數的值。
由於webservice中的selectAllCargoInfo方法的參數爲空,所以對應的,android端調用的時候,arrayList和brrayList的值就是空的。
所以大家在使用的時候,只需要將webservice中的方法寫好,然後寫好DBUtil中的調用參數即可。
--->2013.03.23 增加內容
如果獲取值爲空,可能是返回值是複雜類型造成的,可以參考:http://blog.csdn.net/zhyl8157121/article/details/8709048
--->2014.07.18 增加內容
沒想到這麼長時間了還能得到大家的青睞,很欣慰。
之前收到過一些同學發來的郵件,問題大概以下幾種,這裏統一答覆一下吧,希望給有問題的同學一個參考。
0.Webservice無法正確執行(這個沒什麼說的,webservice有問題)
1.Webservice用本地的電腦可以訪問,但是在手機瀏覽器中就無法得到正確的結果(Webservice配置問題,或者IIS配置問題)
2.Webservice用本地的電腦和手機瀏覽器都可以正確執行,但是程序一運行就崩潰
2.1 可能情況1 - 我的程序是用Android2.1寫的,Android2.3以後有一個StrictMode的問題,如果有同學是用2.3以上版本做的,可能是這個問題,具體可以搜索一下StrictMode,然後修改一下程序即可,我在這裏就不獻醜了。
2.2 可能情況2 - 調試的時候是用的是模擬器,IP地址當時填寫的是10.0.2.2,這個地址是PC相對於模擬器的IP地址,放到真機中就不行了,真機運行程序中要填寫PC的IP地址(可以將手機和PC連接在同一個局域網中做測試,也可以將程序發佈到服務器上,Android程序中填寫服務器的IP地址和端口號)。
3.用模擬器調試怎麼都可以,但放到真機上就不行。
3.1 可能情況1 - 模擬器的版本是2.3以下的,程序運行正常,可是真機是2.3以上的,解決方法參考2.1。
3.2 可能情況2 - 放到真機運行的時候沒改程序的url,IP地址錯誤,解決方法參考2.2。
4.SQL語句錯誤、按鈕監聽錯誤等問題大家細心查查就行了。
不出什麼意外的話,本文不會再更新了,樓主已經很久不搞Android了,有些東西也稍微有點生疏了。
以前有些同學給我發郵件或者私信我是每個都回復的,不管問的問題我自己會不會。工作了之後就比較忙了,而且Gmail經常上不去(你懂的),有些同學的郵件就沒有回覆,在此向那些我沒有回覆的同學說聲抱歉,大家都是來交流的,我絕對不是高傲或者懶散,交個朋友也好。
大家不要問QQ號了,那個東西不太適合技術交流,還是郵箱來的實在,這能讓彼此的思考時間多一些。
再次留下我的郵箱:[email protected] 如果有什麼問題,歡迎大家來信交流。
謝謝支持,歡迎大家批評指正。