Hello!
I have a problem between the picture gallery and the mediastore in my android application when i use the camera intent in my fragment.
I checked on the android website to learn how to take a picture in a fragment and on some forums to know how to get the last picture took but the media store always give me the last-1th picture as if it was not able to find the last picture.
This is my code :
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.i(LOG_TAG,"ERRRRROR: "+ex.toString());
}
if (photoFile != null) {
mCurrentPhotoPath = "file:" +photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQ_CAMERA_PICTURE);
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mCurrentPhotoUri = contentUri;
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
Log.d(LOG_TAG,"Photo SAVED");
}
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 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoAbsolutePath = image.getAbsolutePath();
Log.i(LOG_TAG,"image path : "+image.getAbsolutePath());
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CAMERA_PICTURE)
{
if (resultCode == Activity.RESULT_OK)
{
galleryAddPic();
String filePath = getActivity().getPreferences(Context.MODE_PRIVATE).getString(TMP_PHOTO_FILE_LATEST_KEY, null);
handleCameraPicture(mCurrentPhotoUri.toString());
}
else
{
clearCurrentActionData();
}
}
}
private String getLastImagePath() {
String[] projection = new String[]{
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.MIME_TYPE
};
final Cursor cursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
if (cursor.moveToFirst()) {
String imageLocation = cursor.getString(1);
File imageFile = new File(imageLocation);
Bitmap bm = BitmapFactory.decodeFile(imageLocation);
return imageFile.getPath().toString();
}
else{
return "";
}
}
The problem occurs HERE when i try to get the last image path
private void handleCameraPicture(String pictureFileUri)
{
_currentDataObjectBuilder.addParameter(DataObject.Parameter.IMAGE, String.valueOf(getFileCount()));
//create a copy of the file into the internal storage
final File pictureFile = new File(pictureFileUri);
Log.d(LOG_TAG,"picture file uri : "+pictureFileUri.toString());
FileOutputStream fos =null;
byte[] pictureData = new byte[0];
try
{
pictureData = compressImage(getLastImagePath());
fos = getActivity().openFileOutput(String.valueOf(getFileCount()), Context.MODE_PRIVATE);
fos.write(pictureData);
Log.i(LOG_TAG,"SETTING FILE OUTPUT STREAM");
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
try {
fos.close();
pictureFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
if (_currentAction.equals(Action.PICTURE_CAPTION) || _currentAction.equals(Action.ARCHIVE))
{
showMessageView();
}
else
{
sendCurrentActionData();
}
}
The handleCameraPicture function allows me to send the "last picture" to an external website.
I don't know what i do wrong so please help me! I'm gonna lose my mind else...
Thank you!
Thomas
Wouw!
I finally found the solution, actually the uri when i created the picture was different from the one when i tried to save the picture in the gallery so my cursor dropped a null pointer exception.
I updated my GalleryAddPic function to
private void galleryAddPic(Uri uri) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mCurrentPhotoUri = uri;
mediaScanIntent.setData(uri);
getActivity().sendBroadcast(mediaScanIntent);
Log.d(LOG_TAG,"Photo SAVED");
}
And now everything works fine!
Related
Short answer is it possible to get original file from Gallery request,and if it possible how can i do it? This code doesn't work for me.
Uri uri = data.getData();
File file = new File(uri.getPath());
And the long Answer)):
I use this code to make gallery intent
addGallery.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_IMAGE_REQUEST);
}
});
In mu onActivityResult i use this code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
switch (requestCode)
{
case GALLERY_IMAGE_REQUEST:
if (data != null)
{
try
{
Uri uri = data.getData();
File file = new File(uri.getPath());
FileInputStream inputStream = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
inputStream.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
And i cant get file.
The same code with getting bitmap from data works well but i need to get exactly file from gallery but not only Uri or Bitmap.
try
{
Uri uri = data.getData();
InputStream imageStream = getContentResolver().openInputStream(uri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
imageStream.close();
} catch (Exception e)
{
e.printStackTrace();
}
If you want to import a picture from gallery into your app (in a case your app own it), you need to copy it to your app data folder.
in your onActivityResult():
if (requestCode == REQUEST_TAKE_PHOTO_FROM_GALLERY && resultCode == RESULT_OK) {
try {
// Creating file
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.d(TAG, "Error occurred while creating the file");
}
InputStream inputStream = getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(photoFile);
// Copying
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "onActivityResult: " + e.toString());
}
}
Creating the file method:
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 = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
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;
}
Copy method:
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
I can't take a picture from the camera and then store it as a Bitmap object. I can only find solutions where I get thumbnail as Bitmap. How can I do this?
Here is the code:
public boolean pickImageFromCamera(View View) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try
{
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
photo.delete();
}
catch(Exception e)
{
System.out.println("ERROR TAKING PICTURE");
return false;
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
//start camera intent
activity.startActivityForResult(intent, REQUEST_CODE2);
return true;
}
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
public void pickImageFromFolder(View View) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , REQUEST_CODE);//one can be replaced with any action code
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE2 && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
Bitmap bitmap = null;
this.getContentResolver().notifyChange(mImageUri, null);
ContentResolver cr = this.getContentResolver();
try
{
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
imageView.setImageBitmap(bitmap);
}
catch (Exception e)
{
System.out.println("Failed to load");
}
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
this.UPLOAD_URL = Config.webSiteUrl + "?action=uploadFile&username=" + this.username + "&password=" + this.password + "&baustelleid=" + Fotos.this.baustelleid;
if(bitmap != null) {
uploadImage(bitmap, this.UPLOAD_URL);
}
} catch (Exception e) {
System.out.println("Fehler 1");
}
super.onActivityResult(requestCode, resultCode, data);
}
It ends up with System.out.println("ERROR TAKING PICTURE"); It seems like there is no permission to write the storage. How can I change this?
Call this method in button etc. after that get bitmap onActivityResult
private void dispatchTakePictureIntent() {
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;
File photoThumbnailFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.yourfileprovider",
photoFile);
photoThumbnailURI = FileProvider.getUriForFile(this,
"com.example.yourfileprovider",
photoThumbnailFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
This method will Create file
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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
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;
}
This method will happen when the camera is done taking the picture
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoURI);
mImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You will get a bitmap, but you can get the whole one, not just the thumbnail.
Have you tried this answer ? https://stackoverflow.com/a/6449092/4127441
I have a CardActivity that opens a CameraActivity. I have an imagebutton I press and then the native camera app opens and I can take a picture. I try to pass that back to my CardActivity using an intent with a ByteArray. But it gives me a blank white screen. It doesnt insert anything into the imageview. The Bitmap element is not null, it has something.
This is my switch for starting the camera activity and setting image:
switch (v.getId()) {
case R.id.pButton1:
Intent cam = new Intent(CardActivity.this, CameraActivity.class);
startActivity(cam);
returnImage2();
mImageView = (ImageView)findViewById(R.id.imageView);
mImageView.setImageBitmap(bitmap);
mImageView.setRotation(180);
break;
This is my returnImage2();
public void returnImage2() {
try {
bitmap = BitmapFactory.decodeStream(this.openFileInput("myImage"));
}
catch (Exception e) {
e.printStackTrace();
}
}
This is my cameraActivity:
public class CameraActivity extends Activity {
private String mCurrentPhotoPath;
private ImageView mImageView;
private Bitmap mImageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dispatchTakePictureIntent();
}
public void dispatchTakePictureIntent() {
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) {
// Error occurred while creating the File
System.out.println("ERR CANNOT CREATE FILE");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private File createImageFile2() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
cImageFromBitmap(mImageBitmap);
//mImageView = (ImageView)findViewById(R.id.imageView);
//mImageView.setImageBitmap(mImageBitmap);
//mImageView.setRotation(180);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String cImageFromBitmap(Bitmap bitmap){
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
}
I noticed you are using REQUEST_TAKE_PHOTO for starting your activity
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO)
but you are checking for REQUEST_IMAGE_CAPTURE on onActivityResult
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
ALSO:
I don't know why you are going through all this work to create a file. When you use ACTION_IMAGE_CAPTURE the bitmap itself comes back in the result intent:
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
mImageBitmap = (Bitmap) data.getExtras().get("data");
I am calling the default camera app in my Activity to capture an image. I followed the guide on the Android Site.
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 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
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;
}
private void dispatchTakePictureIntent() {
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 (Exception e) {
e.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Now camera launches and i capture the image. When i am returned to my app via onActivityResult the image does not appear to be saved.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
//convert the image to base64
Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e){
e.printStackTrace();
Toast.makeText(context, "Whoops! Some error occured while taking that photo. Please try again.", Toast.LENGTH_LONG).show();
}
}
}
The BITMAP is NULL.
Why is it null??
You are not initializing your file path. Try this:
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();
Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
I have read a lot of questions regarding this problem. Some are similar to what I am experiencing; I have tried the answers with no success. The code works on a HTC Android 4.2 and doesn't work on a Nexus 7 Android 4.4. I have modified the storage directory to work on android 4.4, so this isn't the problem.
The camera intent never returns if I use
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
and does return if I use
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFile);
but it doesn't save the file.
Here is the full code.
Call the intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(manager) != null)
{
try
{
final File photoFile = createImageFile();
if (photoFile != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFile);
startActivityForResult(takePictureIntent, 1);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
The file name
private File createImageFile() throws IOException
{
if (mStorageDirectory == null)
{
createInitialStorageDirectory();
setupFolders();
mScrollList.notifyDataSetInvalidated();
}
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "slide_" + timeStamp;
File storageDir = new File(mStorageDirectory);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
// image.setWritable(true, false);
// Save a path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
The callback function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1)
{
}
}
The root directory plus the save directory
static String mBasePath = "/slides/";
private String getRootDirectory()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
if (Build.VERSION.SDK_INT >= 19)
return mView.getContext().getFilesDir() + mBasePath;
else
return Environment.getExternalStorageDirectory() + "/Android/data/com.hdms.manager" + mBasePath;
//return Environment.getExternalStorageDirectory() + mBasePath;
}
return mBasePath;
}
Any thoughts would be appreciated.
In my case, it did not return because the output file was inside a folder which I have not created yet.
If it is the case for someone else, do this before starting anintent:
file.getParentFile().mkdirs();
So I have found a solution to my problem. If a file doesn't exist then the Camera Activity will not return. I guess the reason that it doesn't work on 4.4 is the change to the files system. I am not saving the image to the media gallery and loading the file back into my apps directory. The media file is then deleted. The reason that I don't leave it in the media directory, is when the app is deleted so will the images be deleted.
Here is the new code. First the intent call
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(manager) != null)
{
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION,"From your Camera");
Uri mImageUri = App.mApplication.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
mCurrentPhotoPath = mImageUri.getPath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(takePictureIntent, 1);
}
Then the callback.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1)
{
if (data != null)
mCurrentPhotoPath = String.valueOf(data.getData());
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = App.mApplication.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, null, null, null);
if (cursor == null)
return;
// find the file in the media area
cursor.moveToLast();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
File source = new File(filePath);
cursor.close();
// create the destination file
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "slide_" + timeStamp;
File destination = new File(mStorageDirectory, imageFileName + ".jpg");
// copy the data
if (source.exists())
{
try
{
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
source.delete();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
In our scenario our app is able to launch the camera app either via a 'button' click or an 'imageview' click. When using the button route the camera app correctly returned to the calling Activity as expected, however when tapping the imageview the results were inconsistent - sometimes it would return and sometimes the back button had to be tapped several times.
Turns out the solution was my oversight: I was not removing the event handler for the imageview in the OnPause method - once I did then it worked perfectly.