1. 使用Android 3.2 (API level 13)以上(含),以下為程式碼實作(紅字為重點程式碼)
<activity
android:name="com.example.app.MainActivity"
android:configChanges="orientation|screenSize"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
2. 使用Android 3.1 (API level 12)以下(含),以下為程式碼實作(紅字為重點程式碼)
<activity
android:name="com.example.app.MainActivity"
android:configChanges="orientation"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Android Code筆記本
Android Technology development experience to share with you
Android連線Web Service讀取MySQL(新增-讀取圖片格式)
開發環境,如以下清單
1. 啟動 appserv-win32-2.5.10.exe ,並以系統管理員身分執行
2. 建置MySQL環境-part1
3. 建置MySQL環境-part2
4. 建置MySQL環境-part3 (選擇軟體安裝路徑)
5. 建置MySQL環境-part4
6. 建置MySQL環境-part5
7. 建置MySQL環境-part6(帳號密碼為root)
8. 建置MySQL環境-part7
9. 建置MySQL環境-part8(開啟Browser輸入http://localhost:8088/phpMyAdmin/網址,帳密為root)
10 .建立picturedb資料庫
11. 建立picture表格(下列為SQL語法)
CREATE TABLE picture (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
path TEXT NOT NULL
) ENGINE = MYISAM ;
12. 在主機上的C槽底下建立名稱為picture的目錄
實作建立Web Service with java
1. 開啟 Eclipse EE
2. 建立Tomcat Server,請點選以下連結
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. 建立PictureWSP.java-part1
11. 建立PictureWSP.java-part2
12. PictureWSP.java程式碼
package com.picture.wsp;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class PictureWSP {
private String write_db_identified = "write picture to mysql",
read_db_identified = "read picture to android client";
private String url = "jdbc:mysql://localhost/picturedb";
private String driver = "com.mysql.jdbc.Driver";
private String userName = "root";
private String userPassword = "root";
private Connection conndb;
private String pathDir = "C:\\picture\\";
private String pathDB = "C:\\\\picture\\\\";
private String sqlInsert = "insert into picture(path) values(?)",
sqlSelect = "select path from picture order by id asc";
private PreparedStatement insertPreparedStatement;
private String checkWriteStr = "write picture with fail";
private ResultSet resultSet;
public String writePictureToDB(String write_db_identified,
String picture_name, String byte_array_picture) {
try {
if (this.write_db_identified.equals(write_db_identified)) {
if (connWriteDB()) {
if (writePictureInformationToDB(formatPath(pathDB,
picture_name))
& writePictureDataToDir(
formatPath(pathDir, picture_name),
byte_array_picture)) {
checkWriteStr = "write picture with success";
conndb.close();
}
}
}
} catch (Exception io) {
System.out.println(io.getMessage());
try {
conndb.close();
} catch (SQLException e) {
}
}
return checkWriteStr;
}
public byte[] readPictureToAndroidClient(String read_db_identified) {
ArrayList<String> imageArrayList = new ArrayList<String>();
FileInputStream fileInputStream = null;
ByteArrayOutputStream writePicture = null, convertData = null;
ObjectOutputStream objectOutputStream = null;
try {
if (this.read_db_identified.equals(read_db_identified)) {
if (connReadDB()) {
while (resultSet.next()) {
int data = 0;
String readData = resultSet.getString("path");
fileInputStream = new FileInputStream(readData);
writePicture = new ByteArrayOutputStream();
while ((data = fileInputStream.read()) != -1) {
writePicture.write(data);
}
String dataBase = Base64.encode(writePicture
.toByteArray());
imageArrayList.add(dataBase);
}
fileInputStream.close();
writePicture.close();
convertData = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(convertData);
objectOutputStream.writeObject(imageArrayList);
convertData.close();
objectOutputStream.close();
}
}
} catch (Exception io) {
try {
System.out.println(io.toString());
fileInputStream.close();
writePicture.close();
imageArrayList = null;
} catch (IOException e) {
}
}
return convertData.toByteArray();
}
public boolean writePictureInformationToDB(String path) throws Exception {
insertPreparedStatement.setString(1, path);
int checkInsert = insertPreparedStatement.executeUpdate();
if (checkInsert > 0) {
return true;
}
return false;
}
public boolean writePictureDataToDir(String path, String data)
throws Exception {
byte[] bytearray = Base64.decode(data);
FileOutputStream fos = new FileOutputStream(path);
fos.write(bytearray);
fos.close();
return true;
}
public boolean connReadDB() throws Exception {
try {
Class.forName(driver);
conndb = DriverManager.getConnection(url, userName, userPassword);
Statement statement = conndb.createStatement();
resultSet = statement.executeQuery(sqlSelect);
} catch (Exception io) {
return false;
}
return true;
}
public boolean connWriteDB() throws Exception {
try {
Class.forName(driver);
conndb = DriverManager.getConnection(url, userName, userPassword);
insertPreparedStatement = conndb.prepareStatement(sqlInsert);
} catch (Exception io) {
return false;
}
return true;
}
public String formatPath(String... pictureName) {
StringBuilder stringBuilder = new StringBuilder();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd_HH-mm-ss");
stringBuilder.append(pictureName[0])
.append(simpleDateFormat.format(new Date())).append("_")
.append(pictureName[1]).append(".jpg");
return stringBuilder.toString();
}
}
13. 針對PictureWSP建立Web Service並產生wsdl檔-part1
14. 針對PictureWSP建立Web Service並產生wsdl檔-part2
15. 查詢wsdl檔-part1
16. 查詢wsdl檔-part2
17. 查詢wsdl檔-part3
18. 查詢wsdl檔-part4
19. 上網輸入 http://localhost:8080/PictureWSP/services/PictureWSP?wsdl (可更改localhost為你的IP Address,Android會透過wsdl將資料在雲端進行操作)
20. 以下為wsdl檔的模樣
21. 匯入MySQL的JDBC Driver-part1(下列為連結網址)
22. 匯入MySQL的JDBC Driver-part2
23. 下載完成並安裝,到C:\Program Files (x86)\MySQL\MySQL Connector J目錄下可找到mysql-connector-java-5.1.31-bin.jar
24. 匯入MySQL的JDBC Driver(將mysql-connector-java-5.1.31-bin.jar複製到專案裡的WebContent/WEB-INF/lib)
建立Android Client,並整合Web Service與MySQL
1. 開啟Eclipse ADT
2. 建立專案-part1
3. 建立專案-part2
4. 建立專案-part3(一直按Next到如下畫面)
5.匯入SOAP.jar檔,以下網址有教你如何匯入到專案
下列為Android程式碼
1. PictureAppActivity.java
package com.example.pictureapp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
public class PictureAppActivity extends Activity {
private Button selectBtn, nextBtn, preBtn, uploadBtn, upn_Btn;
private ImageView show_picture_IV;
private ToggleButton readtogBtn, writetogBtn;
private int selectCount_UP, GALLERY_INTENT = 100, CAMERA_INTENT = 200;
private String write_db_identified = "write picture to mysql",
read_db_identified = "read picture to android client";
private String WSDL_URL = "http://1.164.114.145:8080/PictureWSP/services/PictureWSP?wsdl";
//紅字為你的IP Address
private String NAMESPACE = "http://wsp.picture.com";
private String SOAP_ACTION_WP = "http://wsp.picture.com/writePictureToDB",
SOAP_ACTION_RP = "http://wsp.picture.com/readPictureToAndroidClient";
private String WPI_METHOD_PARAMETER = "write_db_identified",
WPD_METHOD_PARAMETER = "byte_array_picture",
WPN_METHOD_PARAMETER = "picture_name",
RPI_METHOD_PARAMETER = "read_db_identified";
private String WP_METHOD = "writePictureToDB",
RP_METHOD = "readPictureToAndroidClient";
private String sendWS_picture_Name;
private Bitmap pictureBitmap2;
private ArrayList<Bitmap> picture;
private int showCount;
private File photo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture_app);
processView();
controlView();
}
public void processView() {
selectBtn = (Button) this.findViewById(R.id.select_pic_Btn);
nextBtn = (Button) this.findViewById(R.id.next_Btn);
preBtn = (Button) this.findViewById(R.id.pre_Btn);
uploadBtn = (Button) this.findViewById(R.id.upload_Btn);
upn_Btn = (Button) this.findViewById(R.id.upn_Btn);
readtogBtn = (ToggleButton) this.findViewById(R.id.read_togBtn);
writetogBtn = (ToggleButton) this.findViewById(R.id.write_togBtn);
show_picture_IV = (ImageView) this.findViewById(R.id.picture_IV);
picture = new ArrayList<Bitmap>();
}
public void controlView() {
selectBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
callPictureDialog();
}
});
nextBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
nextData();
}
});
preBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
preData();
}
});
uploadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (selectCount_UP != 0) {
new PictureAppActivity.WritePictureTask().execute(
write_db_identified, WSDL_URL, NAMESPACE,
SOAP_ACTION_WP, WPI_METHOD_PARAMETER,
WPN_METHOD_PARAMETER, WPD_METHOD_PARAMETER,
WP_METHOD, sendWS_picture_Name);
} else {
Toast.makeText(PictureAppActivity.this,
"Please read picture", Toast.LENGTH_SHORT).show();
}
}
});
readtogBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean isChecked) {
if (isChecked) {
setReadOnBtn();
new PictureAppActivity.ReadPictureTask().execute(
read_db_identified, WSDL_URL, NAMESPACE,
SOAP_ACTION_RP, RPI_METHOD_PARAMETER, RP_METHOD);
} else {
setReadOffBtn();
setImageForOrigen();
clearArrayListForPictureData();
}
}
});
writetogBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean isChecked) {
if (isChecked) {
setWriteOnBtn();
} else {
setWriteOffBtn();
}
}
});
upn_Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (selectCount_UP != 0) {
callUpdatePictureNameAlertDialog();
} else {
Toast.makeText(PictureAppActivity.this,
"Please read picture", Toast.LENGTH_SHORT).show();
}
}
});
}
public void callUpdatePictureNameAlertDialog() {
final EditText upn_ET = new EditText(this);
upn_ET.setText(sendWS_picture_Name);
AlertDialog pictureAlertDialog = new AlertDialog.Builder(this).create();
pictureAlertDialog.setTitle("Update picture Name");
pictureAlertDialog.setView(upn_ET);
pictureAlertDialog.setButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendWS_picture_Name = upn_ET.getText().toString();
}
});
pictureAlertDialog.setButton2("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
pictureAlertDialog.show();
}
public void setReadOnBtn() {
writetogBtn.setEnabled(false);
selectBtn.setEnabled(false);
nextBtn.setEnabled(true);
preBtn.setEnabled(true);
uploadBtn.setEnabled(false);
upn_Btn.setEnabled(false);
}
public void setReadOffBtn() {
writetogBtn.setEnabled(true);
selectBtn.setEnabled(false);
nextBtn.setEnabled(false);
preBtn.setEnabled(false);
uploadBtn.setEnabled(false);
upn_Btn.setEnabled(false);
}
public void setWriteOnBtn() {
readtogBtn.setEnabled(false);
selectBtn.setEnabled(true);
nextBtn.setEnabled(false);
preBtn.setEnabled(false);
uploadBtn.setEnabled(true);
upn_Btn.setEnabled(true);
}
public void setWriteOffBtn() {
readtogBtn.setEnabled(true);
selectBtn.setEnabled(false);
nextBtn.setEnabled(false);
preBtn.setEnabled(false);
uploadBtn.setEnabled(false);
upn_Btn.setEnabled(false);
}
public void callPictureDialog() {
AlertDialog pictureAlertDialog = new AlertDialog.Builder(this).create();
pictureAlertDialog.setTitle("Select source of picture");
pictureAlertDialog.setButton("picture from gallery",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callGalleryIntent();
}
});
pictureAlertDialog.setButton2("picture from camera",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callCameraIntent();
}
});
pictureAlertDialog.show();
}
public void callGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (galleryIntent.resolveActivity(getPackageManager()) != null) {
this.startActivityForResult(galleryIntent, GALLERY_INTENT);
}
}
public void callCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
photo = new File(Environment.getExternalStorageDirectory(),
"picture.jpg");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(cameraIntent, CAMERA_INTENT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (resultCode == RESULT_OK) {
String picturePath = "";
if (requestCode == GALLERY_INTENT) {
picturePath = getPicture(data);
}
if (requestCode == CAMERA_INTENT) {
picturePath = photo.toString();
sendWS_picture_Name = "Camera_";
}
setPictureFromGalleryOrCameraImageView(picturePath);
}
} catch (Exception io) {
Log.e("error", io.toString());
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getPicture(Intent data) {
String[] pictureInformation = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME };
Uri selectedImage = data.getData();
Cursor cursor = getContentResolver().query(selectedImage,
pictureInformation, null, null, null);
cursor.moveToFirst();
int dataIndex = cursor.getColumnIndex(pictureInformation[0]);
int nameIndex = cursor.getColumnIndex(pictureInformation[1]);
String picturePath = cursor.getString(dataIndex);
String pictureName = cursor.getString(nameIndex);
cursor.close();
sendWS_picture_Name = pictureName;
return picturePath;
}
public void setPictureFromGalleryOrCameraImageView(String picturePath)
throws Exception {
ExifInterface exifInterface = new ExifInterface(picturePath);
Matrix matrix = new Matrix();
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
matrix.postRotate(270);
}
Bitmap pictureBitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(picturePath), 300, 300, true);
pictureBitmap2 = Bitmap.createBitmap(pictureBitmap, 0, 0,
pictureBitmap.getWidth(), pictureBitmap.getHeight(), matrix,
true);
show_picture_IV.setImageBitmap(pictureBitmap2);
if (photo != null) {
photo.delete();
}
selectCount_UP = 1;
}
private class WritePictureTask extends AsyncTask<String, Void, String> {
private ProgressDialog progresslog;
private String result;
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(PictureAppActivity.this, 1);
progresslog.setCancelable(false);
progresslog.setMessage("Write picture to database...");
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.show();
}
@Override
protected String doInBackground(String... sendData) {
try {
result = handlePictureToWSD(sendData);
} catch (Exception io) {
Log.e("WritePicture", io.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
progresslog.dismiss();
showMessage(result);
setImageForOrigen();
selectCount_UP = 0;
}
public void showMessage(String message) {
Toast.makeText(PictureAppActivity.this, message, Toast.LENGTH_SHORT)
.show();
}
public String handlePictureToWSD(String... sendData) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pictureBitmap2.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream);
String base64_Str = Base64.encode(byteArrayOutputStream
.toByteArray());
SoapObject requestWS = new SoapObject(sendData[2], sendData[7]);
PropertyInfo writerPI = new PropertyInfo();
writerPI.setName(sendData[4]);
writerPI.setValue(sendData[0]);
writerPI.setType(String.class);
requestWS.addProperty(writerPI);
PropertyInfo writerPN = new PropertyInfo();
writerPN.setName(sendData[5]);
writerPN.setValue(sendData[8]);
writerPN.setType(String.class);
requestWS.addProperty(writerPN);
PropertyInfo writerPD = new PropertyInfo();
writerPD.setName(sendData[6]);
writerPD.setValue(base64_Str);
writerPD.setType(String.class);
requestWS.addProperty(writerPD);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(requestWS);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
sendData[1]);
androidHttpTransport.call(sendData[3], envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
return response.toString();
}
}
private class ReadPictureTask extends AsyncTask<String, Void, String> {
private ProgressDialog progresslog;
private String readSuccess, result;
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(PictureAppActivity.this, 1);
progresslog.setCancelable(false);
progresslog.setMessage("Read picture ...");
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.show();
}
@Override
protected String doInBackground(String... sendData) {
try {
result = handlePictureToAC(sendData);
} catch (Exception io) {
Log.e("error", io.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
progresslog.dismiss();
showData(showCount);
Toast.makeText(PictureAppActivity.this, result, Toast.LENGTH_SHORT)
.show();
}
public String handlePictureToAC(String... sendData) throws Exception {
SoapObject requestWS = new SoapObject(sendData[2], sendData[5]);
PropertyInfo readPI = new PropertyInfo();
readPI.setName(sendData[4]);
readPI.setValue(sendData[0]);
readPI.setType(String.class);
requestWS.addProperty(readPI);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(requestWS);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
sendData[1]);
androidHttpTransport.call(sendData[3], envelope);
SoapPrimitive soapPrimitive = (SoapPrimitive) envelope
.getResponse();
byte[] information = android.util.Base64.decode(soapPrimitive
.toString().getBytes(), android.util.Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
information);
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
ArrayList<String> arraylist_student = (ArrayList<String>) objectInputStream
.readObject();
for (int i = 0; i < arraylist_student.size(); i++) {
byte[] decodedString = android.util.Base64.decode(
arraylist_student.get(i), android.util.Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
picture.add(bitmap);
}
if (picture.size() == arraylist_student.size()) {
readSuccess = "read picture with success";
} else {
readSuccess = "read picture with fail";
}
return readSuccess;
}
}
public void clearArrayListForPictureData() {
picture.clear();
showCount = 0;
}
public void showData(int index) {
if (picture != null) {
if (picture.size() != 0) {
show_picture_IV.setImageBitmap(picture.get(showCount));
} else {
Toast.makeText(this, "Please insert picture",
Toast.LENGTH_SHORT).show();
}
}
}
public void nextData() {
if (picture != null) {
showCount++;
if (showCount >= picture.size()) {
showCount = 0;
}
setAnimationForPicture(show_picture_IV);
showData(showCount);
}
}
public void preData() {
if (picture != null) {
showCount--;
if (showCount < 0) {
showCount = picture.size() - 1;
}
setAnimationForPicture(show_picture_IV);
showData(showCount);
}
}
public void setAnimationForPicture(ImageView imageView) {
imageView.setAnimation(AnimationUtils.loadAnimation(
getApplicationContext(), android.R.anim.slide_in_left));
}
public void setImageForOrigen() {
show_picture_IV.setImageResource(R.drawable.ic_launcher);
}
}
2. activity_picture_app.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PictureAppActivity" >
<RelativeLayout
android:id="@+id/image_view_relativeLayout"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<ImageSwitcher
android:id="@+id/picture_ISW"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" >
<ImageView
android:id="@+id/picture_IV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</ImageSwitcher>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/select_pic_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Select picture" />
<Button
android:id="@+id/upload_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Upload picture" />
<Button
android:id="@+id/upn_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Update picture Name"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/pre_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="previous" />
<Button
android:id="@+id/next_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="next" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read picture : "
android:textSize="20sp" />
<ToggleButton
android:id="@+id/read_togBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="off"
android:textOn="on" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write picture : "
android:textSize="20sp" />
<ToggleButton
android:id="@+id/write_togBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="off"
android:textOn="on" />
</LinearLayout>
</LinearLayout>
3. AndroidManifest.xml (重點程式碼)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- 作業系統環境
Microsoft Window 7(64 bit)
- AppServ (Tomcat + MySQL + phpMyAdmin) 軟體 (包含下載連結網址)
AppServ
- 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讀取MySQL資料庫的資料
- Android Client透過Web Service讀取MySQL的所有資料,該資料為圖片存於主機上的路徑位置,透過該路徑讀取圖片,並回傳到Android Client UI顯示圖片
2. 透過Web Service寫入資料到MySQL資料庫
實作步驟
- 在Android Client讀取一張圖片,並透過Web Service將Android Client所讀取的圖片寫入到主機的目錄上並將主機目錄上的路徑寫入MySQL
1. 建立MySQL資料庫MySQL資料庫設計實作
2. 建立Web Service with java
3. 建立Android Client,並整合Web Service與MySQL
1. 啟動 appserv-win32-2.5.10.exe ,並以系統管理員身分執行
2. 建置MySQL環境-part1
3. 建置MySQL環境-part2
4. 建置MySQL環境-part3 (選擇軟體安裝路徑)
5. 建置MySQL環境-part4
6. 建置MySQL環境-part5
7. 建置MySQL環境-part6(帳號密碼為root)
8. 建置MySQL環境-part7
9. 建置MySQL環境-part8(開啟Browser輸入http://localhost:8088/phpMyAdmin/網址,帳密為root)
10 .建立picturedb資料庫
11. 建立picture表格(下列為SQL語法)
CREATE TABLE picture (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
path TEXT NOT NULL
) ENGINE = MYISAM ;
12. 在主機上的C槽底下建立名稱為picture的目錄
實作建立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. 建立PictureWSP.java-part1
11. 建立PictureWSP.java-part2
12. PictureWSP.java程式碼
package com.picture.wsp;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class PictureWSP {
private String write_db_identified = "write picture to mysql",
read_db_identified = "read picture to android client";
private String url = "jdbc:mysql://localhost/picturedb";
private String driver = "com.mysql.jdbc.Driver";
private String userName = "root";
private String userPassword = "root";
private Connection conndb;
private String pathDir = "C:\\picture\\";
private String pathDB = "C:\\\\picture\\\\";
private String sqlInsert = "insert into picture(path) values(?)",
sqlSelect = "select path from picture order by id asc";
private PreparedStatement insertPreparedStatement;
private String checkWriteStr = "write picture with fail";
private ResultSet resultSet;
public String writePictureToDB(String write_db_identified,
String picture_name, String byte_array_picture) {
try {
if (this.write_db_identified.equals(write_db_identified)) {
if (connWriteDB()) {
if (writePictureInformationToDB(formatPath(pathDB,
picture_name))
& writePictureDataToDir(
formatPath(pathDir, picture_name),
byte_array_picture)) {
checkWriteStr = "write picture with success";
conndb.close();
}
}
}
} catch (Exception io) {
System.out.println(io.getMessage());
try {
conndb.close();
} catch (SQLException e) {
}
}
return checkWriteStr;
}
public byte[] readPictureToAndroidClient(String read_db_identified) {
ArrayList<String> imageArrayList = new ArrayList<String>();
FileInputStream fileInputStream = null;
ByteArrayOutputStream writePicture = null, convertData = null;
ObjectOutputStream objectOutputStream = null;
try {
if (this.read_db_identified.equals(read_db_identified)) {
if (connReadDB()) {
while (resultSet.next()) {
int data = 0;
String readData = resultSet.getString("path");
fileInputStream = new FileInputStream(readData);
writePicture = new ByteArrayOutputStream();
while ((data = fileInputStream.read()) != -1) {
writePicture.write(data);
}
String dataBase = Base64.encode(writePicture
.toByteArray());
imageArrayList.add(dataBase);
}
fileInputStream.close();
writePicture.close();
convertData = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(convertData);
objectOutputStream.writeObject(imageArrayList);
convertData.close();
objectOutputStream.close();
}
}
} catch (Exception io) {
try {
System.out.println(io.toString());
fileInputStream.close();
writePicture.close();
imageArrayList = null;
} catch (IOException e) {
}
}
return convertData.toByteArray();
}
public boolean writePictureInformationToDB(String path) throws Exception {
insertPreparedStatement.setString(1, path);
int checkInsert = insertPreparedStatement.executeUpdate();
if (checkInsert > 0) {
return true;
}
return false;
}
public boolean writePictureDataToDir(String path, String data)
throws Exception {
byte[] bytearray = Base64.decode(data);
FileOutputStream fos = new FileOutputStream(path);
fos.write(bytearray);
fos.close();
return true;
}
public boolean connReadDB() throws Exception {
try {
Class.forName(driver);
conndb = DriverManager.getConnection(url, userName, userPassword);
Statement statement = conndb.createStatement();
resultSet = statement.executeQuery(sqlSelect);
} catch (Exception io) {
return false;
}
return true;
}
public boolean connWriteDB() throws Exception {
try {
Class.forName(driver);
conndb = DriverManager.getConnection(url, userName, userPassword);
insertPreparedStatement = conndb.prepareStatement(sqlInsert);
} catch (Exception io) {
return false;
}
return true;
}
public String formatPath(String... pictureName) {
StringBuilder stringBuilder = new StringBuilder();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd_HH-mm-ss");
stringBuilder.append(pictureName[0])
.append(simpleDateFormat.format(new Date())).append("_")
.append(pictureName[1]).append(".jpg");
return stringBuilder.toString();
}
}
13. 針對PictureWSP建立Web Service並產生wsdl檔-part1
14. 針對PictureWSP建立Web Service並產生wsdl檔-part2
15. 查詢wsdl檔-part1
16. 查詢wsdl檔-part2
17. 查詢wsdl檔-part3
18. 查詢wsdl檔-part4
19. 上網輸入 http://localhost:8080/PictureWSP/services/PictureWSP?wsdl (可更改localhost為你的IP Address,Android會透過wsdl將資料在雲端進行操作)
20. 以下為wsdl檔的模樣
21. 匯入MySQL的JDBC Driver-part1(下列為連結網址)
MySQL JDBC Driver Download
22. 匯入MySQL的JDBC Driver-part2
23. 下載完成並安裝,到C:\Program Files (x86)\MySQL\MySQL Connector J目錄下可找到mysql-connector-java-5.1.31-bin.jar
24. 匯入MySQL的JDBC Driver(將mysql-connector-java-5.1.31-bin.jar複製到專案裡的WebContent/WEB-INF/lib)
建立Android Client,並整合Web Service與MySQL
1. 開啟Eclipse ADT
2. 建立專案-part1
3. 建立專案-part2
4. 建立專案-part3(一直按Next到如下畫面)
5.匯入SOAP.jar檔,以下網址有教你如何匯入到專案
匯入SOAP.jar
下列為Android程式碼
1. PictureAppActivity.java
package com.example.pictureapp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
public class PictureAppActivity extends Activity {
private Button selectBtn, nextBtn, preBtn, uploadBtn, upn_Btn;
private ImageView show_picture_IV;
private ToggleButton readtogBtn, writetogBtn;
private int selectCount_UP, GALLERY_INTENT = 100, CAMERA_INTENT = 200;
private String write_db_identified = "write picture to mysql",
read_db_identified = "read picture to android client";
private String WSDL_URL = "http://1.164.114.145:8080/PictureWSP/services/PictureWSP?wsdl";
//紅字為你的IP Address
private String NAMESPACE = "http://wsp.picture.com";
private String SOAP_ACTION_WP = "http://wsp.picture.com/writePictureToDB",
SOAP_ACTION_RP = "http://wsp.picture.com/readPictureToAndroidClient";
private String WPI_METHOD_PARAMETER = "write_db_identified",
WPD_METHOD_PARAMETER = "byte_array_picture",
WPN_METHOD_PARAMETER = "picture_name",
RPI_METHOD_PARAMETER = "read_db_identified";
private String WP_METHOD = "writePictureToDB",
RP_METHOD = "readPictureToAndroidClient";
private String sendWS_picture_Name;
private Bitmap pictureBitmap2;
private ArrayList<Bitmap> picture;
private int showCount;
private File photo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture_app);
processView();
controlView();
}
public void processView() {
selectBtn = (Button) this.findViewById(R.id.select_pic_Btn);
nextBtn = (Button) this.findViewById(R.id.next_Btn);
preBtn = (Button) this.findViewById(R.id.pre_Btn);
uploadBtn = (Button) this.findViewById(R.id.upload_Btn);
upn_Btn = (Button) this.findViewById(R.id.upn_Btn);
readtogBtn = (ToggleButton) this.findViewById(R.id.read_togBtn);
writetogBtn = (ToggleButton) this.findViewById(R.id.write_togBtn);
show_picture_IV = (ImageView) this.findViewById(R.id.picture_IV);
picture = new ArrayList<Bitmap>();
}
public void controlView() {
selectBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
callPictureDialog();
}
});
nextBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
nextData();
}
});
preBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
preData();
}
});
uploadBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (selectCount_UP != 0) {
new PictureAppActivity.WritePictureTask().execute(
write_db_identified, WSDL_URL, NAMESPACE,
SOAP_ACTION_WP, WPI_METHOD_PARAMETER,
WPN_METHOD_PARAMETER, WPD_METHOD_PARAMETER,
WP_METHOD, sendWS_picture_Name);
} else {
Toast.makeText(PictureAppActivity.this,
"Please read picture", Toast.LENGTH_SHORT).show();
}
}
});
readtogBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean isChecked) {
if (isChecked) {
setReadOnBtn();
new PictureAppActivity.ReadPictureTask().execute(
read_db_identified, WSDL_URL, NAMESPACE,
SOAP_ACTION_RP, RPI_METHOD_PARAMETER, RP_METHOD);
} else {
setReadOffBtn();
setImageForOrigen();
clearArrayListForPictureData();
}
}
});
writetogBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean isChecked) {
if (isChecked) {
setWriteOnBtn();
} else {
setWriteOffBtn();
}
}
});
upn_Btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (selectCount_UP != 0) {
callUpdatePictureNameAlertDialog();
} else {
Toast.makeText(PictureAppActivity.this,
"Please read picture", Toast.LENGTH_SHORT).show();
}
}
});
}
public void callUpdatePictureNameAlertDialog() {
final EditText upn_ET = new EditText(this);
upn_ET.setText(sendWS_picture_Name);
AlertDialog pictureAlertDialog = new AlertDialog.Builder(this).create();
pictureAlertDialog.setTitle("Update picture Name");
pictureAlertDialog.setView(upn_ET);
pictureAlertDialog.setButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sendWS_picture_Name = upn_ET.getText().toString();
}
});
pictureAlertDialog.setButton2("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
pictureAlertDialog.show();
}
public void setReadOnBtn() {
writetogBtn.setEnabled(false);
selectBtn.setEnabled(false);
nextBtn.setEnabled(true);
preBtn.setEnabled(true);
uploadBtn.setEnabled(false);
upn_Btn.setEnabled(false);
}
public void setReadOffBtn() {
writetogBtn.setEnabled(true);
selectBtn.setEnabled(false);
nextBtn.setEnabled(false);
preBtn.setEnabled(false);
uploadBtn.setEnabled(false);
upn_Btn.setEnabled(false);
}
public void setWriteOnBtn() {
readtogBtn.setEnabled(false);
selectBtn.setEnabled(true);
nextBtn.setEnabled(false);
preBtn.setEnabled(false);
uploadBtn.setEnabled(true);
upn_Btn.setEnabled(true);
}
public void setWriteOffBtn() {
readtogBtn.setEnabled(true);
selectBtn.setEnabled(false);
nextBtn.setEnabled(false);
preBtn.setEnabled(false);
uploadBtn.setEnabled(false);
upn_Btn.setEnabled(false);
}
public void callPictureDialog() {
AlertDialog pictureAlertDialog = new AlertDialog.Builder(this).create();
pictureAlertDialog.setTitle("Select source of picture");
pictureAlertDialog.setButton("picture from gallery",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callGalleryIntent();
}
});
pictureAlertDialog.setButton2("picture from camera",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callCameraIntent();
}
});
pictureAlertDialog.show();
}
public void callGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (galleryIntent.resolveActivity(getPackageManager()) != null) {
this.startActivityForResult(galleryIntent, GALLERY_INTENT);
}
}
public void callCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
photo = new File(Environment.getExternalStorageDirectory(),
"picture.jpg");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(cameraIntent, CAMERA_INTENT);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (resultCode == RESULT_OK) {
String picturePath = "";
if (requestCode == GALLERY_INTENT) {
picturePath = getPicture(data);
}
if (requestCode == CAMERA_INTENT) {
picturePath = photo.toString();
sendWS_picture_Name = "Camera_";
}
setPictureFromGalleryOrCameraImageView(picturePath);
}
} catch (Exception io) {
Log.e("error", io.toString());
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getPicture(Intent data) {
String[] pictureInformation = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME };
Uri selectedImage = data.getData();
Cursor cursor = getContentResolver().query(selectedImage,
pictureInformation, null, null, null);
cursor.moveToFirst();
int dataIndex = cursor.getColumnIndex(pictureInformation[0]);
int nameIndex = cursor.getColumnIndex(pictureInformation[1]);
String picturePath = cursor.getString(dataIndex);
String pictureName = cursor.getString(nameIndex);
cursor.close();
sendWS_picture_Name = pictureName;
return picturePath;
}
public void setPictureFromGalleryOrCameraImageView(String picturePath)
throws Exception {
ExifInterface exifInterface = new ExifInterface(picturePath);
Matrix matrix = new Matrix();
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
matrix.postRotate(270);
}
Bitmap pictureBitmap = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(picturePath), 300, 300, true);
pictureBitmap2 = Bitmap.createBitmap(pictureBitmap, 0, 0,
pictureBitmap.getWidth(), pictureBitmap.getHeight(), matrix,
true);
show_picture_IV.setImageBitmap(pictureBitmap2);
if (photo != null) {
photo.delete();
}
selectCount_UP = 1;
}
private class WritePictureTask extends AsyncTask<String, Void, String> {
private ProgressDialog progresslog;
private String result;
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(PictureAppActivity.this, 1);
progresslog.setCancelable(false);
progresslog.setMessage("Write picture to database...");
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.show();
}
@Override
protected String doInBackground(String... sendData) {
try {
result = handlePictureToWSD(sendData);
} catch (Exception io) {
Log.e("WritePicture", io.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
progresslog.dismiss();
showMessage(result);
setImageForOrigen();
selectCount_UP = 0;
}
public void showMessage(String message) {
Toast.makeText(PictureAppActivity.this, message, Toast.LENGTH_SHORT)
.show();
}
public String handlePictureToWSD(String... sendData) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pictureBitmap2.compress(Bitmap.CompressFormat.JPEG, 100,
byteArrayOutputStream);
String base64_Str = Base64.encode(byteArrayOutputStream
.toByteArray());
SoapObject requestWS = new SoapObject(sendData[2], sendData[7]);
PropertyInfo writerPI = new PropertyInfo();
writerPI.setName(sendData[4]);
writerPI.setValue(sendData[0]);
writerPI.setType(String.class);
requestWS.addProperty(writerPI);
PropertyInfo writerPN = new PropertyInfo();
writerPN.setName(sendData[5]);
writerPN.setValue(sendData[8]);
writerPN.setType(String.class);
requestWS.addProperty(writerPN);
PropertyInfo writerPD = new PropertyInfo();
writerPD.setName(sendData[6]);
writerPD.setValue(base64_Str);
writerPD.setType(String.class);
requestWS.addProperty(writerPD);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(requestWS);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
sendData[1]);
androidHttpTransport.call(sendData[3], envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
return response.toString();
}
}
private class ReadPictureTask extends AsyncTask<String, Void, String> {
private ProgressDialog progresslog;
private String readSuccess, result;
@Override
protected void onPreExecute() {
progresslog = new ProgressDialog(PictureAppActivity.this, 1);
progresslog.setCancelable(false);
progresslog.setMessage("Read picture ...");
progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progresslog.show();
}
@Override
protected String doInBackground(String... sendData) {
try {
result = handlePictureToAC(sendData);
} catch (Exception io) {
Log.e("error", io.toString());
}
return result;
}
@Override
protected void onPostExecute(String result) {
progresslog.dismiss();
showData(showCount);
Toast.makeText(PictureAppActivity.this, result, Toast.LENGTH_SHORT)
.show();
}
public String handlePictureToAC(String... sendData) throws Exception {
SoapObject requestWS = new SoapObject(sendData[2], sendData[5]);
PropertyInfo readPI = new PropertyInfo();
readPI.setName(sendData[4]);
readPI.setValue(sendData[0]);
readPI.setType(String.class);
requestWS.addProperty(readPI);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(requestWS);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
sendData[1]);
androidHttpTransport.call(sendData[3], envelope);
SoapPrimitive soapPrimitive = (SoapPrimitive) envelope
.getResponse();
byte[] information = android.util.Base64.decode(soapPrimitive
.toString().getBytes(), android.util.Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
information);
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
ArrayList<String> arraylist_student = (ArrayList<String>) objectInputStream
.readObject();
for (int i = 0; i < arraylist_student.size(); i++) {
byte[] decodedString = android.util.Base64.decode(
arraylist_student.get(i), android.util.Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
picture.add(bitmap);
}
if (picture.size() == arraylist_student.size()) {
readSuccess = "read picture with success";
} else {
readSuccess = "read picture with fail";
}
return readSuccess;
}
}
public void clearArrayListForPictureData() {
picture.clear();
showCount = 0;
}
public void showData(int index) {
if (picture != null) {
if (picture.size() != 0) {
show_picture_IV.setImageBitmap(picture.get(showCount));
} else {
Toast.makeText(this, "Please insert picture",
Toast.LENGTH_SHORT).show();
}
}
}
public void nextData() {
if (picture != null) {
showCount++;
if (showCount >= picture.size()) {
showCount = 0;
}
setAnimationForPicture(show_picture_IV);
showData(showCount);
}
}
public void preData() {
if (picture != null) {
showCount--;
if (showCount < 0) {
showCount = picture.size() - 1;
}
setAnimationForPicture(show_picture_IV);
showData(showCount);
}
}
public void setAnimationForPicture(ImageView imageView) {
imageView.setAnimation(AnimationUtils.loadAnimation(
getApplicationContext(), android.R.anim.slide_in_left));
}
public void setImageForOrigen() {
show_picture_IV.setImageResource(R.drawable.ic_launcher);
}
}
2. activity_picture_app.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PictureAppActivity" >
<RelativeLayout
android:id="@+id/image_view_relativeLayout"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<ImageSwitcher
android:id="@+id/picture_ISW"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" >
<ImageView
android:id="@+id/picture_IV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</ImageSwitcher>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/select_pic_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Select picture" />
<Button
android:id="@+id/upload_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Upload picture" />
<Button
android:id="@+id/upn_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="Update picture Name"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/pre_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="previous" />
<Button
android:id="@+id/next_Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false"
android:text="next" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read picture : "
android:textSize="20sp" />
<ToggleButton
android:id="@+id/read_togBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="off"
android:textOn="on" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write picture : "
android:textSize="20sp" />
<ToggleButton
android:id="@+id/write_togBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="off"
android:textOn="on" />
</LinearLayout>
</LinearLayout>
3. AndroidManifest.xml (重點程式碼)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
訂閱:
文章 (Atom)