- 作業系統環境
Microsoft Window 7(64 bit)
32bit的ODBC執行程式 (C:\Windows\SysWOW64\odbcad32.exe)
- 資料庫
MS Access 2007
- Web Service開發軟體(包含下載連結網址)
Apache Axis2 Release 1.6.2 (Binary Distribution zip)
Apache Tomcat 7.0.54 - 32bit
Eclipse IDE for java EE Developers - 32bit
- Android開發軟體
Eclipse ADT - 64bit實作說明
- 本專案有以下兩種功能
1. 透過Web Service讀取MS Access資料庫的資料
- Android Client發生請求時,Web Service讀取MS Access資料庫的資料,並使用雲端運算功能(轉換成byte array的資料結構),並將資料回傳前端顯示在Android Client UI
2. 透過Web Service寫入資料到MS Access資料庫
實作步驟
- Android Client UI有三個輸入方框(EditText),並針對這三個輸入方框輸入數值,這三個數值會透過SOAP協議方式傳輸到雲端,透過雲端運算寫入MS Access
1. 建立MS Access 2007資料庫,設定ODBCMS Access資料庫設計實作
2. 建立Web Service with java
3. 建立Android Client,並整合Web Service與MS Access
1. 開啟MS Access 2007資料庫,並選擇資料庫儲存路徑
2. 輸入表格名稱
3. 設計表格架構(設定id欄位)
4. 設計表格架構(設定student_id欄位)
5. 設計表格架構(設定student_name欄位)
6. 設計表格架構(設定score欄位)
7. 點選資料表兩下
8. 新增一筆資料,並關閉MS Access 2007
9. 到 C:\Windows\SysWOW64\odbcad32.exe(Window 7) 路徑設定ODBC
10. 設定ODBC驅動程式
11. 設定資料庫來源路徑
12. 搜尋資料庫儲存位置
13. 輸入資料庫名稱
實作建立Web Service with java
1. 開啟 Eclipse EE
2. 建立Tomcat Server,請點選以下連結
建立Tomcat Server 網址3. 安裝axis2-part1
4. 安裝axis2-part2(點選Browse,選擇axis2解壓縮檔的路徑)
5. 安裝axis2-part3(設定web service與server執行環境)
6.建立 Web Service環境-part1
7. 建立 Web Service環境-part2
8. 建立 Web Service環境-part3
9. 建立 Web Service環境-part4(點選Modify)
10. 建立StudentWSApp.java-part1
11. 建立StudentWSApp.java-part2
12. 建立Student.java-part1
13. 建立Student.java-part2
14. 建立SendStudent.java(這邊的package name必須跟android的package name相同,因為在雲端傳輸的資料必須要序列化)-part1
15. 建立SendStudent.java-part2
16. StudentWSApp.java程式碼
package com.app.studentWS;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import com.example.webserviceapp.SendStudent;
public class StudentWSApp {
private String url = "jdbc:odbc:studentdb";
private String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
private static Connection conndb;
private String identified_conn_pass = "Connect MS Access 2007 Database",
identified_disconn_pass = "Disconnect MS Access 2007 Database",
identified_wmsdb_pass = "Writer MS Access 2007 Database",
identified_rmsdb_pass = "Read MS Access 2007 Database";
private String sqlInsert = "insert into student(student_id,student_name,score) values(?,?,?)",
sqlSelect = "select * from student order by id";
private static PreparedStatement insertPreparedStatement;
private boolean isCheckConnectionDB = false;
public boolean connectDB(String identified_conn_number) {
if (identified_conn_number.equals(identified_conn_pass)) {
try {
Class.forName(driver);
conndb = DriverManager.getConnection(url);
insertPreparedStatement = conndb.prepareStatement(sqlInsert);
isCheckConnectionDB = true;
} catch (Exception io) {
System.out.println(io.getMessage());
isCheckConnectionDB = false;
}
}
return isCheckConnectionDB;
}
public boolean disconnectDB(String identified_disconn_number) {
boolean isCheckDisConnectionDB = false;
if (identified_disconn_number.equals(identified_disconn_pass)) {
try {
conndb.close();
conndb = null;
isCheckDisConnectionDB = true;
} catch (SQLException e) {
}
}
return isCheckDisConnectionDB;
}
public byte[] readMSAccessDatabase(String readMSDB) {
if (readMSDB.equals(identified_rmsdb_pass)) {
ArrayList<Student> studentArrayList = new ArrayList<Student>();
ObjectOutputStream objectOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
System.out.println(Thread.currentThread().getName().toString()
+ " size = " + studentArrayList.size());
try {
Statement statement = conndb.createStatement();
ResultSet resultSet = statement.executeQuery(sqlSelect);
while (resultSet.next()) {
Student student = new Student(
resultSet.getString("student_id"),
resultSet.getString("student_name"),
resultSet.getString("score"));
studentArrayList.add(student);
}
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(
byteArrayOutputStream);
objectOutputStream.writeObject(studentArrayList);
} catch (Exception e) {
System.out.println(e.toString());
}
System.out.println(Thread.currentThread().getName().toString()
+ " size = " + studentArrayList.size());
return byteArrayOutputStream.toByteArray();
}
return null;
}
public String writerMSAccessDatabase(String writerMSDB,
byte[] student_byte_array) {
if (writerMSDB.equals(identified_wmsdb_pass)) {
String checkStr = "";
SendStudent sendStudent = null;
ObjectInputStream objectInputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
try {
byteArrayInputStream = new ByteArrayInputStream(
student_byte_array);
objectInputStream = new ObjectInputStream(byteArrayInputStream);
sendStudent = (SendStudent) objectInputStream.readObject();
if (writerMSDB.equals(identified_wmsdb_pass)) {
if (insertPreparedStatement != null) {
insertPreparedStatement.setInt(1,
sendStudent.getStudentId());
insertPreparedStatement.setString(2,
sendStudent.getStudentName());
insertPreparedStatement.setDouble(3,
sendStudent.getStudentScore());
int checkInsert = insertPreparedStatement
.executeUpdate();
if (checkInsert > 0) {
checkStr = "Confirm insert";
}
}
}
} catch (Exception io) {
checkStr = io.toString();
}
return checkStr;
}
return null;
}
}
17. Student.java程式碼
package com.app.studentWS;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 4363540466857453349L;
private String student_id;
private String student_name;
private String score;
public Student(String student_id, String student_name, String score) {
this.student_id = student_id;
this.student_name = student_name;
this.score = score;
}
public String getStudentId() {
return student_id;
}
public String getStudentName() {
return student_name;
}
public String getStudentScore() {
return score;
}
}
18. SendStudent .java程式碼
package com.example.webserviceapp;
import java.io.Serializable;
public class SendStudent implements Serializable {
private int student_id;
private String student_name;
private double score;
private static final long serialVersionUID = -13900787737978801L;
public SendStudent(int student_id, String student_name, double score) {
this.student_id = student_id;
this.student_name = student_name;
this.score = score;
}
public int getStudentId() {
return student_id;
}
public String getStudentName() {
return student_name;
}
public double getStudentScore() {
return score;
}
}
19. 針對StudentWSApp建立Web Service並產生wsdl檔-part1
20. 針對StudentWSApp建立Web Service並產生wsdl檔-part2
21. 查詢wsdl檔-part1
22. 查詢wsdl檔-part2
23. 查詢wsdl檔-part3
24. 查詢wsdl檔-part4
25. 上網輸入 http://localhost:8080/StudentWSApp/services/StudentWSApp?wsdl (可更改localhost為你的IP Address,Android會透過wsdl將資料在雲端進行操作)
26. 以下為wsdl檔的模樣
建立Android Client,並整合Web Service與MS Access
1. 開啟Eclipse ADT
2. 建立專案-part1
3. 建立專案-part2
4. 建立專案-part3(一直按Next到如下畫面)
5.匯入SOAP.jar檔,以下網址有教你如何匯入到專案
匯入SOAP.jar
下列為Android程式碼
1. WebServiceApp .java
package com.example.webserviceapp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import com.app.studentWS.Student;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
public class WebServiceApp extends Activity {
private Button read, writer, next, previous;
private EditText id_et, name_et, score_et;
private Switch writer_SWH, conndb_SWH;
private static int WIFI_CONNECTED_STATUS = 0,
MOBILE_INTERNET_CONNECTED_STATUS = 1;
private InternetConnectionDetector internetDB;
private Boolean isConnectionExist = false;
public final static String URL = "http://220.139.97.199:8080/StudentWSApp/services/StudentWSApp?wsdl"; //紅字部分為host的IP Address
public static final String NAMESPACE = "http://studentWS.app.com";
public static final String SOAP_ACTION_CONNDB = "http://studentWS.app.com/connectDB",
SOAP_ACTION_DISCONNDB = "http://studentWS.app.com/disconnectDB",
SOAP_ACTION_RMSDB = "http://studentWS.app.com/readMSAccessDatabase",
SOAP_ACTION_WMSDB = "http://studentWS.app.com/writerMSAccessDatabase";
private static final String CONNDB_METHOD = "connectDB",
DISCONNDB_METHOD = "disconnectDB",
RMSDB_METHOD = "readMSAccessDatabase",
WMSDB_METHOD = "writerMSAccessDatabase";
private static final String identified_conn_pass = "Connect MS Access 2007 Database",
identified_disconn_pass = "Disconnect MS Access 2007 Database",
identified_rmsdb_pass = "Read MS Access 2007 Database",
identified_wmsdb_pass = "Writer MS Access 2007 Database";
private static final String conndb_methodParameter = "identified_conn_number",
disconndb_methodParameter = "identified_disconn_number",
rmsdb_methodParameter = "readMSDB",
wmsdb_student_methodParameter = "student_byte_array",
wmsdb_methodParameter = "writerMSDB";
private static final String taskConnDB = "conndb",
taskDisConnDB = "disconndb";
private int doubleCheck = 0;
private String progressContent;
private ArrayList<Student> arrayListStudent;
private int rowCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_service_app);
processView();
processControl();
}
public void processView() {
internetDB = new InternetConnectionDetector(getApplicationContext());
read = (Button) this.findViewById(R.id.readBtn);
writer = (Button) this.findViewById(R.id.writerBtn);
next = (Button) this.findViewById(R.id.nextBtn);
previous = (Button) this.findViewById(R.id.preBtn);
id_et = (EditText) this.findViewById(R.id.id_ET);
name_et = (EditText) this.findViewById(R.id.name_ET);
score_et = (EditText) this.findViewById(R.id.score_ET);
writer_SWH = (Switch) this.findViewById(R.id.write_SWH);
conndb_SWH = (Switch) this.findViewById(R.id.conndb_SWH);
writer.setEnabled(false);
}
public void processControl() {
writer_SWH.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundBtn,
boolean checked) {
new WebServiceApp.CheckDBConnTask(compoundBtn).execute(checked);
}
});
conndb_SWH.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundBtn,
boolean checked) {
if (checked) {
if (isCheckInternetConnect()) {
connectDB();
} else {
doubleCheck = 1;
AlertDialog alertDialog = new AlertDialog.Builder(
WebServiceApp.this).create();
alertDialog.setTitle("No Internet Connection");
// Setting Dialog Message
alertDialog
.setMessage("Your device doesn't have Internet access");
// Setting alert dialog icon
alertDialog.setIcon(android.R.drawable.ic_delete);
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
conndb_SWH.setChecked(false);
}
});
alertDialog.show();
}
} else {
if (doubleCheck == 0) {
disconnectDB();
setRestoreContent(compoundBtn);
}
}
}
});
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (conndb_SWH.isChecked()) {
readMSAccessDB();
} else {
Toast.makeText(WebServiceApp.this,
"Please connect Database", Toast.LENGTH_SHORT)
.show();
}
}
});
writer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
try {
int student_id = Integer.parseInt(id_et.getText()
.toString());
String student_name = name_et.getText().toString();
double score_name = Double.parseDouble(score_et.getText()
.toString());
SendStudent student = new SendStudent(student_id,
student_name, score_name);
new WebServiceApp.WMSDBTask().execute(student);
} catch (Exception io) {
Toast.makeText(WebServiceApp.this,
"Please input correct format", Toast.LENGTH_SHORT)
.show();
}
}
});
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (!id_et.getText().toString().equals("")) {
nextData();
} else {
Toast.makeText(WebServiceApp.this, "Please read data",
Toast.LENGTH_SHORT).show();
}
}
});
previous.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (!id_et.getText().toString().equals("")) {
preData();
} else {
Toast.makeText(WebServiceApp.this, "Please read data",
Toast.LENGTH_SHORT).show();
}
}
});
}
public void readMSAccessDB() {
new WebServiceApp.RMSDBTask().execute(identified_rmsdb_pass);
}
public void setClearContent() {
id_et.setText("");
name_et.setText("");
score_et.setText("");
id_et.setHint("Please input data");
name_et.setHint("Please input data");
score_et.setHint("Please input data");
read.setEnabled(false);
next.setEnabled(false);
previous.setEnabled(false);
writer.setEnabled(true);
id_et.setFocusableInTouchMode(true);
name_et.setFocusableInTouchMode(true);
score_et.setFocusableInTouchMode(true);
}
public void setRestoreContent(View view) {
id_et.setText("");
name_et.setText("");
score_et.setText("");
id_et.setHint("Please read data");
name_et.setHint("Please read data");
score_et.setHint("Please read data");
read.setEnabled(true);
next.setEnabled(true);
previous.setEnabled(true);
writer.setEnabled(false);
id_et.setFocusable(false);
name_et.setFocusable(false);
score_et.setFocusable(false);
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
public boolean isCheckInternetConnect() {
isConnectionExist = internetDB.checkMobileInternetConn();
if (isConnectionExist) {
return true;
}
return false;
}
public void connectDB() {
doubleCheck = 0;
new WebServiceApp.DBTask().setProgressContent("CODB");
new WebServiceApp.DBTask().execute(identified_conn_pass,
conndb_methodParameter, SOAP_ACTION_CONNDB, CONNDB_METHOD,
taskConnDB);
}
public void disconnectDB() {
new WebServiceApp.DBTask().setProgressContent("DISCODB");
new WebServiceApp.DBTask().execute(identified_disconn_pass,
disconndb_methodParameter, SOAP_ACTION_DISCONNDB,
DISCONNDB_METHOD, taskDisConnDB);
}
private class InternetConnectionDetector {
private Context context;
public InternetConnectionDetector(Context context) {
this.context = context;
}
public boolean checkMobileInternetConn() {
// Create object for ConnectivityManager class which returns network
// related info
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// If connectivity object is not null
if (connectivity != null) {
// Get network info - WIFI internet access
NetworkInfo[] internetInfo = {
connectivity
.getNetworkInfo(ConnectivityManager.TYPE_WIFI),
connectivity
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) };
if (internetInfo[WIFI_CONNECTED_STATUS] != null
|| internetInfo[MOBILE_INTERNET_CONNECTED_STATUS] != null) {
// Look for whether device is currently connected to WIFI
// network
if (internetInfo[WIFI_CONNECTED_STATUS].isConnected()
|| internetInfo[MOBILE_INTERNET_CONNECTED_STATUS]
.isConnected()) {
return true;
}
}
}
return false;
}
}
private class CheckDBConnTask extends AsyncTask<Boolean, Integer, Boolean> {
private View view;
public CheckDBConnTask(View view) {
this.view = view;
}
@Override
protected void onPreExecute() {
}
@Override
protected Boolean doInBackground(Boolean... isConnCheck) {
return isConnCheck[0];
}
@Override
protected void onPostExecute(Boolean result) {
if (conndb_SWH.isChecked()) {
if (result) {
setClearContent();
} else {
setRestoreContent(view);
}
} else {
writer_SWH.setChecked(false);
Toast.makeText(WebServiceApp.this,
"Please connection database", Toast.LENGTH_SHORT)
.show();
}
}
}
private class DBTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progresslog;
private String chooseTost;
public void setProgressContent(String content) {
progressContent = content;
}
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(WebServiceApp.this, 1);
progresslog.setCancelable(false);
if (progressContent.equals("CODB")) {
progresslog.setMessage("Connect Database...");
} else if (progressContent.equals("DISCODB")) {
progresslog.setMessage("DisConnect Database...");
}
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.show();
}
@Override
protected String doInBackground(String... connStr) {
chooseTost = connStr[4];
boolean isCheckedConn = false;
SoapObject requestWS = new SoapObject(NAMESPACE, connStr[3]);
PropertyInfo connInfoP = new PropertyInfo();
connInfoP.setName(connStr[1]);// Define the variable
// name in the web
// service method
connInfoP.setValue(connStr[0]); // Define value for
// identified_number variable
connInfoP.setType(String.class); // Define the type of the variable
requestWS.addProperty(connInfoP);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(requestWS);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(connStr[2], envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
isCheckedConn = Boolean.parseBoolean(response.toString());
} catch (Exception io) {
Log.e("error", io.toString());
}
return String.valueOf(isCheckedConn);
}
@Override
protected void onPostExecute(String result) {
boolean isConnect = Boolean.valueOf(result);
if (isConnect) {
if (chooseTost.equals(taskConnDB)) {
Toast.makeText(WebServiceApp.this,
"Connection Database with success",
Toast.LENGTH_SHORT).show();
} else if (chooseTost.equals(taskDisConnDB)) {
Toast.makeText(WebServiceApp.this,
"Database with success disconnect",
Toast.LENGTH_SHORT).show();
writer_SWH.setChecked(false);
rowCount = 0;
}
} else {
if (chooseTost.equals(taskConnDB)) {
doubleCheck = 1;
Toast.makeText(WebServiceApp.this,
"Connection Database with failure",
Toast.LENGTH_SHORT).show();
conndb_SWH.setChecked(false);
} else if (chooseTost.equals(taskDisConnDB)) {
Toast.makeText(WebServiceApp.this,
"Database already disconnect", Toast.LENGTH_SHORT)
.show();
writer_SWH.setChecked(false);
rowCount = 0;
}
}
progresslog.dismiss();
}
}
private class WMSDBTask extends AsyncTask<SendStudent, Integer, String> {
private ProgressDialog progresslog;
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(WebServiceApp.this, 1);
progresslog.setCancelable(false);
progresslog.setMessage("Write data to database...");
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.show();
}
@Override
protected String doInBackground(SendStudent... receiveObj) {
String receiveStr = "";
SoapObject requestWS = new SoapObject(NAMESPACE, WMSDB_METHOD);
ObjectOutputStream objectOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(
byteArrayOutputStream);
objectOutputStream.writeObject(receiveObj[0]);
PropertyInfo writerStudentIP = new PropertyInfo();
writerStudentIP.setName(wmsdb_methodParameter);
writerStudentIP.setValue(identified_wmsdb_pass);
writerStudentIP.setType(String.class);
requestWS.addProperty(writerStudentIP);
PropertyInfo writerStudentBP = new PropertyInfo();
writerStudentBP.setName(wmsdb_student_methodParameter);
writerStudentBP.setValue(byteArrayOutputStream.toByteArray());
writerStudentBP.setType(byte[].class);
requestWS.addProperty(writerStudentBP);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
new MarshalBase64().register(envelope);
envelope.setOutputSoapObject(requestWS);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION_WMSDB, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
receiveStr = response.toString();
} catch (Exception io) {
receiveStr = io.toString();
}
return receiveStr;
}
@Override
protected void onPostExecute(String result) {
progresslog.dismiss();
if (result.equals("Confirm insert")) {
Toast.makeText(WebServiceApp.this, "Insert success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(WebServiceApp.this,
"Database already disconnect", Toast.LENGTH_SHORT)
.show();
}
}
}
private class RMSDBTask extends
AsyncTask<String, Integer, ArrayList<Student>> {
private ProgressDialog progresslog;
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(WebServiceApp.this, 1);
progresslog.setCancelable(false);
progresslog.setMessage("Read data of Database...");
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.setCancelable(false);
progresslog.show();
}
@Override
protected ArrayList<Student> doInBackground(String... connStr) {
ArrayList<Student> soapList = null;
SoapObject requestRWSDB = new SoapObject(NAMESPACE, RMSDB_METHOD);
PropertyInfo rwsdbInfo = new PropertyInfo();
rwsdbInfo.setName(rmsdb_methodParameter);
rwsdbInfo.setValue(connStr[0]);
rwsdbInfo.setType(String.class);
requestRWSDB.addProperty(rwsdbInfo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(requestRWSDB);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION_RMSDB, envelope);
SoapPrimitive soapPrimitive = (SoapPrimitive) envelope
.getResponse();
soapList = handleSoapPrimitiveConvertArrayList(soapPrimitive);
} catch (Exception io) {
Log.e("doInBackground", io.toString());
}
return soapList;
}
@Override
protected void onPostExecute(ArrayList<Student> result) {
try {
rowCount = 0;
initArrayListStudent(result);
showData(0);
progresslog.dismiss();
} catch (Exception io) {
Log.e("onPostExecute", io.toString());
}
}
private ArrayList<Student> handleSoapPrimitiveConvertArrayList(
SoapPrimitive soapPrimitive) {
try {
byte[] information = Base64.decode(soapPrimitive.toString()
.getBytes(), Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
information);
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
ArrayList<Student> arraylist_student = (ArrayList<Student>) objectInputStream
.readObject();
return arraylist_student;
} catch (Exception io) {
return null;
}
}
}
public void initArrayListStudent(ArrayList<Student> result) {
if (arrayListStudent != null) {
arrayListStudent.clear();
}
arrayListStudent = result;
// Log.e("Size", arrayListStudent.size() + "");
}
public void showData(int index) {
if (arrayListStudent != null) {
if (arrayListStudent.size() > 0) {
id_et.setText(arrayListStudent.get(index).getStudentId() + "");
name_et.setText(arrayListStudent.get(index).getStudentName());
score_et.setText(arrayListStudent.get(index).getStudentScore()
+ "");
} else {
Toast.makeText(this, "Please insert data", Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(this, "Database already disconnection",
Toast.LENGTH_SHORT).show();
}
}
public void nextData() {
if (arrayListStudent != null) {
rowCount++;
if (rowCount >= arrayListStudent.size()) {
rowCount = 0;
}
showData(rowCount);
} else {
Toast.makeText(this, "Database already disconnection",
Toast.LENGTH_SHORT).show();
}
}
public void preData() {
if (arrayListStudent != null) {
rowCount--;
if (rowCount < 0) {
rowCount = arrayListStudent.size() - 1;
}
showData(rowCount);
} else {
Toast.makeText(this, "Database already disconnection",
Toast.LENGTH_SHORT).show();
}
}
}
2. SendStudent.java
package com.example.webserviceapp;
import java.io.Serializable;
public class SendStudent implements Serializable {
private static final long serialVersionUID = -13900787737978801L;
private int student_id;
private String student_name;
private double score;
public SendStudent(int student_id, String student_name, double score) {
this.student_id = student_id;
this.student_name = student_name;
this.score = score;
}
}
3. Student.java(注意Student.java的package name必須與Web Service的Student.java的package name一樣)
package com.app.studentWS;
import java.io.Serializable;
public class Student implements Serializable {
private String student_id, student_name, score;
private static final long serialVersionUID = 4363540466857453349L;
public Student(String student_id, String student_name, String score) {
this.student_id = student_id;
this.student_name = student_name;
this.score = score;
}
public String getStudentId() {
return student_id;
}
public String getStudentName() {
return student_name;
}
public String getStudentScore() {
return score;
}
}
4. activity_web_service_app.xml
<?xml version="1.0"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".WebServiceApp" >
<TextView
android:id="@+id/id_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Id : "
android:textColor="@android:color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/id_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:focusable="false"
android:hint="Please read data" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/name_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name : "
android:textColor="@android:color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/name_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:focusable="false"
android:hint="Please read data" />
<TextView
android:id="@+id/score_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score : "
android:textColor="@android:color/black"
android:textSize="20sp" />
<EditText
android:id="@+id/score_ET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:focusable="false"
android:hint="Please read data" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/readBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read" />
<Button
android:id="@+id/writerBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/readBtn"
android:text="Writer" />
<Button
android:id="@+id/preBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/writerBtn"
android:text="Previous" />
<Button
android:id="@+id/nextBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/preBtn"
android:text="Next" />
</RelativeLayout>
<Switch
android:id="@+id/write_SWH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Writer Data" />
<Switch
android:id="@+id/conndb_SWH"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect Database" />
</LinearLayout>
5. AndroidManifest.xml(重點程式碼)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
沒有留言:
張貼留言