編輯:關於 Android 程式設計
本文以實例講解 Android 如何通過 WebService 訪問並操作 SQL Server 數據庫,供感興趣的讀者參考。
首先,在 AndroidManifest.xml 中添加訪問網絡的權限:
<uses-sdk android:minSdkVersion="7" /> <uses-permission android:name="android.permission.INTERNET" />
接著在 src 中新建一個負責連接 WebService 的類,這裡命名為 HttpConnSoap。這個類的結構基本固定,通常需要修改的主要是 WebService 的地址:
package com.example.hospital;//名字要改成自己的包名 import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.util.Xml; public class HttpConnSoap { public ArrayList<String> GetWebServre(String methodName,ArrayList<String> Parameters,ArrayList<String>ParValues) { ArrayList<String> Values=new ArrayList<String>(); String ServerUrl="https://10.0.2.2:8093/Service1.asmx";//網友要改的大多數就是這裡。 //String soapAction="https://tempuri.org/LongUserId1"; String soapAction="https://tempuri.org/"+methodName; String data=""; String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:xsi=\"https://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"https://www.w3.org/2001/XMLSchema\" xmlns:soap=\"https://schemas.xmlsoap.org/soap/envelope/\">" +"<soap:Body />"; String tps,vps,ts; String mreakString=""; mreakString="<"+methodName+" xmlns=\"https://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=\"https://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(8000);// 設置超時時間 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; } }
然後新建一個數據庫訪問類 DBUtil,通過 HttpConnSoap 與底層數據庫通信。這裡定義的方法需要與你在 WebService 中聲明的方法保持一致(本例的 WebService 用 VS2010、.NET 3.5 框架搭建)。以下列舉兩個示例方法:
public class DBUtil { static boolean feeflag=false; ArrayList<String> arrayList=new ArrayList<String>(); ArrayList<String> brrayList=new ArrayList<String>(); ArrayList<String> crrayList=new ArrayList<String>(); HttpConnSoap Soaptest=new HttpConnSoap(); public static Connection getConnection() { Connection con=null; try { System.out.println("111"); Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("222"); con=DriverManager.getConnection("jdbc:mysql://192.168.0.100:3306/test?useUnicode=true&characterEncoding=UTF-8","root","123456"); System.out.println("333"); } catch(Exception e) { System.out.println("444"); e.printStackTrace(); } return con; } //查詢學生信息 public String[] selectStu(String StuNO) { String ss[]=new String[8]; String result=null; arrayList.clear(); brrayList.clear(); crrayList.clear(); arrayList.add("StuNO"); brrayList.add(StuNO); crrayList=Soaptest.GetWebServre("selectStu", arrayList, brrayList); ss[0]=crrayList.get(0); ss[1]=crrayList.get(1); ss[2]=crrayList.get(2); ss[3]=crrayList.get(3); ss[4]=crrayList.get(4); ss[5]=crrayList.get(5); ss[6]=crrayList.get(6); ss[7]=crrayList.get(7); return ss; } public List<HashMap<String, String>> selectStuAll() { List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); arrayList.clear(); brrayList.clear(); crrayList.clear(); crrayList = Soaptest.GetWebServre("selectStuAll", arrayList, brrayList); /*HashMap<String, String> tempHash = new HashMap<String, String>(); tempHash.put("S_Name", "姓名"); tempHash.put("S_Age", "年齡"); tempHash.put("S_Sex", "性別"); list.add(tempHash);*/ for (int j = 0; j < crrayList.size(); j += 3) { HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("S_Name", crrayList.get(j)); hashMap.put("S_Age", crrayList.get(j + 1)); hashMap.put("S_Sex", crrayList.get(j + 2)); list.add(hashMap); } return list; } }
最後在 Activity 中調用,這裡用 ListView 展示查詢到的數據:
private ListView listView; private DBUtil dbUtil; private SimpleAdapter adapter; private void setListView() { List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); list = dbUtil.selectStuAll(); adapter = new SimpleAdapter( DayList.this, list, R.layout.adapter, new String[] { "S_Name", "S_Age", "S_Sex" }, new int[] { R.id.textView1, R.id.textView2, R.id.textView3 }); listView.setAdapter(adapter); }
需要提醒的是,網絡請求應放在子線程中執行,不能在主線程直接操作,否則在新版本 Android 上會拋出 NetworkOnMainThreadException。此外,直接把數據庫連接信息寫死在客戶端存在安全風險,正式項目中更推薦通過後端接口進行訪問。
Android 開發實作:呼叫系統相簿選圖並裁切
「從相簿挑一張圖,順便裁一下」幾乎每個 App 都會遇到。自己刻一套選圖與裁切介面不是不行,但螢幕適配、記憶體、效能全得自己扛;直接叫用系統的在意圖(Intent)反而輕
Android Studio 性能調優(六):GPU Monitor 使用指南
Android Monitor 中包含了 GPU Monitor,它能夠以圖形化的方式直觀地展示窗體的渲染耗時。借助 GPU Monitor,你可以: 迅速查看 UI 窗
Android 開源庫 - PullToRefresh 下拉刷新框架
簡介:PullToRefresh 是一款強大的下拉刷新框架,支持 ListView、GridView、ViewPager、ScrollView、WebView 等一切可拖
用 Android Studio 讀懂 Android 5.x 源碼:從 idegen 到索引完成的完整實踐
做整機開發,最磨人的往往不是寫程式,而是「讀程式」。AOSP 那棵龐大的源碼樹在傳統工具裡幾乎寸步難行,本文要聊的,是如何把這件事交給 Android Studio。 G