私のアプリケーションでは、REST テクノロジを使用して受信するサービスに画像をアップロードしようとしています。
カメラ関数を起動するインテントと onActionResult を設定して画像を処理し、それをサーバーで処理する AsyncTask に渡します。
コード:
package com.testingapp;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class HomeActivity extends Activity {
final static String DEBUG_TAG = "MakePhotoActivity";
protected static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
private Camera camera;
private int cameraId = 0;
HttpEntity resEntity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setTitle("My Relocation");
actionBar.setIcon(R.drawable.menu_ic_launcher);
setContentView(R.layout.activity_home);
Bundle bundle = getIntent().getExtras();
final int cameraId = 0;
final TextView welcomeText = (TextView) findViewById(R.id.WelcomeText);
final TextView relocationId = (TextView) findViewById(R.id.RelocationID);
final TextView addressOne = (TextView) findViewById(R.id.addressOne);
final TextView addressTwo = (TextView) findViewById(R.id.addressTwo);
final String RelocationId = bundle.getString("UID");
relocationId.setText("Your Relocation: #" + RelocationId);
findViewById(R.id.viewMyContacts).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
String UserId = RelocationId;
Intent intent = new Intent(HomeActivity.this,
MoveContactsActivity.class);
intent.putExtra("UID1", UserId);
startActivity(intent);
}
});
findViewById(R.id.viewMyExpenses).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
String UserId = RelocationId;
Intent intent = new Intent(HomeActivity.this,
ViewRecieptsActivity.class);
intent.putExtra("UID3", UserId);
startActivity(intent);
}
});
findViewById(R.id.viewMyMoveDates).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
String UserID1 = RelocationId;
Intent intent = new Intent(HomeActivity.this,
MoveDatesActivity.class);
intent.putExtra("UID2", UserID1);
startActivity(intent);
}
});
findViewById(R.id.viewExpenseReceipts).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
}
});
findViewById(R.id.captureReceiptPhotoButton).setOnClickListener(
new OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View view) {
// if (cameraCheck() == true) {
// camera.takePicture(null, null, new PhotoHandler(
// HomeActivity.this));
// }
String fileName = "TempPhoto";
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, fileName);
values.put(ImageColumns.DESCRIPTION,
"Temporary Photo from Recipt Photo Taker");
File imageUri = new File(Environment.getExternalStorageDirectory(), "com.testingapp/");
if(!imageUri.exists()){
imageUri.mkdir();
}
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
findViewById(R.id.WebAddress).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Uri uri = Uri.parse("http://www.Relocationmw.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
public boolean cameraCheck() {
int Cameras = Camera.getNumberOfCameras();
if (Cameras > 0) {
return true;
} else {
return false;
}
}
private File getTempFile(Context context){
//it should return /sdcard0/TempPhoto
final File path = new File( Environment.getExternalStorageDirectory(), "com.testingapp/" );
if(!path.exists()){
path.mkdir();
}
return new File(path, "TempPhoto");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Bundle CameraBundle = getIntent().getExtras();
// Grab image with Uri, Turn into Image and send through AsyncTask.
final File file = getTempFile(this);
// try {
// Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
new ImageUpload().execute(file);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken",
Toast.LENGTH_SHORT).show();
}
}
}
// Handle the conversion of File to Bitmap for Sending through Intent to
// PhotoPreview
private class ImageUpload extends AsyncTask<File, Void, String> {
@Override
protected void onPreExecute() {
if (checkNullState() == false) {
showMyDialog();
}
}
@Override
protected String doInBackground(File... file) {
String imageDescriptionTemp = "Photo Temp Description.";
String PostRequestUri = "https://demo.relocationmw.com/ws_docmgmt/Service1.svc";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(PostRequestUri);
FileBody bin1 = new FileBody(file[0]);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("Image", bin1);
post.setEntity(entity);
HttpResponse response;
try {
response = client.execute(post);
resEntity = response.getEntity();
final String response_string = EntityUtils.toString(resEntity);
if(resEntity != null){
Log.i("RESPONSE", response_string);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (checkNullState() == true) {
dismissMyDialog();
}
// add location once we have that figured out.
Toast.makeText(HomeActivity.this, "Image can be viewed {Location}",
Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Map... values) {
}
// ProgressDialog Tracking
private ProgressDialog pd1;
private boolean isMyDialogShowing;
boolean checkNullState() {
boolean test;
if (pd1 != null) {
test = true;
} else {
test = false;
}
return test;
}
void showMyDialog() {
isMyDialogShowing = true;
pd1 = new ProgressDialog(HomeActivity.this);
pd1.setTitle("Image Uploading");
pd1.setMessage("Uploading Image....");
pd1.show();
}
void dismissMyDialog() {
pd1.dismiss();
isMyDialogShowing = false;
}
}
}
全体の活動があること。
LogCat は次のとおりです。
04-11 09:51:32.090: W/System.err(26030): java.io.FileNotFoundException: /storage/sdcard0/com.testingapp/TempPhoto: open failed: ENOENT (No such file or directory)
04-11 09:51:32.095: W/System.err(26030): at libcore.io.IoBridge.open(IoBridge.java:416)
04-11 09:51:32.095: W/System.err(26030): at java.io.FileInputStream.<init>(FileInputStream.java:78)
04-11 09:51:32.100: W/System.err(26030): at org.apache.http.entity.mime.content.FileBody.writeTo(FileBody.java:92)
04-11 09:51:32.100: W/System.err(26030): at org.apache.http.entity.mime.HttpMultipart.doWriteTo(HttpMultipart.java:206)
04-11 09:51:32.100: W/System.err(26030): at org.apache.http.entity.mime.HttpMultipart.writeTo(HttpMultipart.java:224)
04-11 09:51:32.105: W/System.err(26030): at org.apache.http.entity.mime.MultipartEntity.writeTo(MultipartEntity.java:183)
04-11 09:51:32.105: W/System.err(26030): at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:97)
04-11 09:51:32.105: W/System.err(26030): at org.apache.http.impl.AbstractHttpClientConnection.sendRequestEntity(AbstractHttpClientConnection.java:162)
04-11 09:51:32.105: W/System.err(26030): at org.apache.http.impl.conn.AbstractClientConnAdapter.sendRequestEntity(AbstractClientConnAdapter.java:272)
04-11 09:51:32.105: W/System.err(26030): at org.apache.http.protocol.HttpRequestExecutor.doSendRequest(HttpRequestExecutor.java:237)
04-11 09:51:32.110: W/System.err(26030): at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:119)
04-11 09:51:32.110: W/System.err(26030): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
04-11 09:51:32.110: W/System.err(26030): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
04-11 09:51:32.110: W/System.err(26030): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
04-11 09:51:32.115: W/System.err(26030): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-11 09:51:32.115: W/System.err(26030): at com.testingapp.HomeActivity$ImageUpload.doInBackground(HomeActivity.java:220)
04-11 09:51:32.115: W/System.err(26030): at com.testingapp.HomeActivity$ImageUpload.doInBackground(HomeActivity.java:1)
04-11 09:51:32.115: W/System.err(26030): at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-11 09:51:32.115: W/System.err(26030): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-11 09:51:32.120: W/System.err(26030): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-11 09:51:32.120: W/System.err(26030): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-11 09:51:32.120: W/System.err(26030): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-11 09:51:32.125: W/System.err(26030): at java.lang.Thread.run(Thread.java:856)
04-11 09:51:32.125: W/System.err(26030): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
04-11 09:51:32.125: W/System.err(26030): at libcore.io.Posix.open(Native Method)
04-11 09:51:32.130: W/System.err(26030): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
04-11 09:51:32.130: W/System.err(26030): at libcore.io.IoBridge.open(IoBridge.java:400)
04-11 09:51:32.130: W/System.err(26030): ... 22 more
インポートが正しいことはほぼ 100% 確信していますが、保存先として指定した場所からファイルを取得できない理由がわかりません。
どんな助けでも大歓迎です!