|
|
|
Android ถ้าจะอัพโหลดรูปภาพที่ถ่าย ไปพร้อมกับฟิลด์อื่น ๆ ทำไงครับ |
|
|
|
|
|
|
|
โค้ด จาวา
Code (Java)
package com.android.passakorn;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.provider.MediaStore;
import android.net.Uri;
public class transfer_form extends Activity implements OnClickListener, OnItemSelectedListener{
private Spinner sp;
private DatePickerDialog dpDateTransfer;
private SimpleDateFormat dateFormat;
private EditText date_transfer,txt_bank_no,txt_cash_transfer;
private TextView rentID,roomID,fullName;
private Button btn_ok_transfer,btn_cancel_transfer;
private MyHttpPoster poster;
////////////////////////////////////////////////////////////////
ImageView imgView ;
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
static String strSDCardPathName = Environment.getExternalStorageDirectory() + "/temp_picture" + "/";
static String strURLUpload = "http://www.luffy.cis-training.com/android/insert_transfer.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.transfer_form);
//////////////////////////////////////////////////////////
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// *** Create Folder
createFolder();
// *** ImageView
imgView = (ImageView) findViewById(R.id.imgUpload);
// *** Take Photo
final Button btnTakePhoto = (Button) findViewById(R.id.btn_choose);
// Perform action on click.
btnTakePhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
});
//////////////////////////////////////////////////////////
final String rent_id = getIntent().getExtras().getString("rent_id").toString();
//Toast.makeText(transfer_form.this," " + rent_id, Toast.LENGTH_SHORT). show();
date_transfer = (EditText)findViewById(R.id.txt_date_transfer);
txt_bank_no = (EditText)findViewById(R.id.txt_bank_no);
txt_cash_transfer = (EditText)findViewById(R.id.txt_cash_transfer);
rentID = (TextView)findViewById(R.id.textView_rentID);
roomID = (TextView)findViewById(R.id.textView_roomID);
fullName = (TextView)findViewById(R.id.textView_fullname);
dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
findViews();
setDateTime();
sp = (Spinner)findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(this);
List<String> items = new ArrayList<String>();
items.add("ธนาคารกรุงเทพ");
items.add("ธนาคารกรุงไทย");
items.add("ธนาคารกรุงศรี");
items.add("ธนาคารกสิกรไทย");
items.add("ธนาคารทหารไทย");
items.add("ธนาคารไทยพานิชย์");
items.add("ธนาคารออมสิน");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
poster = new MyHttpPoster("http://www.luffy.cis-training.com/android/transfer_detail.php");
ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("rent_id", rent_id));
poster.doPost(data, new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what){
case MyHttpPoster.HTTP_POST_ERROR:
Toast.makeText(transfer_form.this,"ตรวจสอบการเชื่อมต่อ Internet", Toast.LENGTH_LONG).show();
break;
case MyHttpPoster.HTTP_POST_OK:
String response = (String)msg.obj;
try {
JSONObject object = new JSONObject(response);
rentID.setText(object.getString("rent_id"));
roomID.setText(object.getString("room_id"));
fullName.setText(object.getString("u_name") + " " + object.getString("u_lastname"));
txt_cash_transfer.setText(object.getString("cash"));
} catch (JSONException e) {
Toast.makeText(transfer_form.this," " + e, Toast.LENGTH_LONG).show();
}
break;
}
};
});
txt_cash_transfer.setEnabled(false);
btn_ok_transfer = (Button)findViewById(R.id.btn_ok_transfer);
btn_ok_transfer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String TextDate = date_transfer.getText().toString().trim();
String bank_no = txt_bank_no.getText().toString().trim();
String cash = txt_cash_transfer.getText().toString().trim();
if(TextDate.length() == 0){
new AlertDialog.Builder(transfer_form.this)
.setMessage("กรุณาเลือกวันที่")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}else if(bank_no.length() == 0){
new AlertDialog.Builder(transfer_form.this)
.setMessage("กรุณากรอกหมายเลขบัญชี")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}else{
uploadFiletoServer(mCurrentPhotoPath, strURLUpload);
Intent i = new Intent();
i = new Intent(getApplicationContext(),insert_transfer.class);
i.putExtra("rent_id", rent_id);
i.putExtra("transfer_date",TextDate);
i.putExtra("bank_name",sp.getSelectedItem().toString());
i.putExtra("bank_no", bank_no);
i.putExtra("cash",cash);
startActivity(i);
finish();
//Toast.makeText(transfer_form.this," " + rent_id + " " + TextDate + " " + sp.getSelectedItem().toString() + " " + bank_no + " " + cash, Toast.LENGTH_LONG).show();
}
}
});
btn_cancel_transfer = (Button)findViewById(R.id.btn_cancel_transfer);
btn_cancel_transfer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void setDateTime() {
date_transfer.setInputType(InputType.TYPE_NULL);
date_transfer.requestFocus();
}
private void findViews() {
date_transfer.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
dpDateTransfer = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
date_transfer.setText(dateFormat.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
if(v == date_transfer) {
dpDateTransfer.show();
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
//Toast.makeText(transfer_form.this, "" + parent.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = new File(strSDCardPathName);
File image = File.createTempFile(imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
imgView.setImageBitmap(bitmap);
}
}
public static boolean uploadFiletoServer(String strSDPath, String strUrlServer) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try{
File file = new File(strSDPath);
if (!file.exists()) {
return false;
}
FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));
URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes(
"Content-Disposition: form-data; name=\"filUpload\";filename=\"" + strSDPath +
"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Response Code and Message
resCode = conn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();
resMessage = new String(result);
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e){
// Exception handling
return false;
}
}
public static void createFolder() {
File folder = new File(strSDCardPathName);
try {
// Create folder
if (!folder.exists()) {
folder.mkdir();
}
} catch (Exception ex) {
}
}
}
โค้ด php
Code (PHP)
<?php
$arr = array();
include("../include/function.php");
connect_db();
$rent_id = $_POST["rent_id"];
$transfer_date = $_POST["transfer_date"];
$bank_name = $_POST["bank_name"];
$cash = $_POST["cash"];
$bank_no = $_POST["bank_no"];
if(isset($_FILES["filUpload"]["name"]) && $_FILES["filUpload"]["tmp_name"] != ''){
$slips = $_FILES["filUpload"]["name"];
$slip_tmp = $_FILES["filUpload"]["tmp_name"];
move_uploaded_file($slip_tmp,"images/slips/$slips");
}else{
$slips = "";
}
/*$rent_id = "00131";
$transfer_date = "2015-11-19";
$bank_name = "ธนาคารกรุงเทพ";
$cash = "300";
$bank_no = "5555555555";*/
/* if(@move_uploaded_file($_FILES["filUpload"]["tmp_name"],"images/slips/".$_FILES["filUpload"]["name"]))
{
$arr["StatusID"] = "1";
$arr["Error"] = "";
}
else
{
$arr["StatusID"] = "0";
$arr["Error"] = "Error cannot upload file.";
}*/
$sql="INSERT INTO transfer VALUES('$rent_id','$bank_name','$bank_no','$cash','$transfer_date','$slips')";
//echo $sql;
mysql_query($sql)or die(mysql_error());
$sql1="UPDATE rent SET rent_status ='2' WHERE rent_id = '$rent_id' ";
//echo $sql1;
mysql_query($sql1)or die(mysql_error());
//echo json_encode($arr);
?>
Tag : Mobile, MySQL, Android, JAVA, Mobile
|
ประวัติการแก้ไข 2015-11-21 19:24:19
|
|
|
|
|
Date :
2015-11-21 19:18:58 |
By :
backman19 |
View :
1102 |
Reply :
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
คือรูปที่ผมถ่ายเป็นแนวตั้ง แต่แสดงใน ImageView มันเป็นแนวนอนครับ
เวลาผมเรียกจากฐานข้อมูลมา มันก็แสดงเป็นแนวนอน T^T ต้องเซ็ตไว้ส่วนไหนหรอครับ ...?
|
|
|
|
|
Date :
2015-11-25 01:25:02 |
By :
backman19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ลองใช้การ Rotate ลองดู Library พวก Image Loader ครับ ทำได้หลายอย่าง
Android Image Library (Image Library)
|
|
|
|
|
Date :
2015-11-25 09:00:18 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 04
|