Bitmap is null in onActivityResult after MediaStore.ACTION_IMAGE_CAPTURE - android

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);

Related

Android Studio get File from Gallery Intent

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);
}
}

Failure delivering result ResultInfo in Android development for Camera Activity

I am trying to capture an image and go to next intent with the image. This following code going to Camera Intent. But not going to second intent. Its returning java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity error. that means there is no data going to onResultActivity. If I put data!=null in the argument then its returning to 1st Activity. What I am missing? I have tested the mCurrentPhotoPath. Its returning the filePath.
String shopName;
double latitude, longitude;
private int REQUEST_IMAGE_CAPTURE = 0;
private Bitmap imageBitmap;
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 0;
private File createImageFile() throws IOException {
// Create an image file name
#SuppressLint("SimpleDateFormat") 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;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
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
}
if (photoFile != null) {
//Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
"com.marketaccess.data.collector.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode != RESULT_CANCELED) {
Uri filePath = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] imageResource = stream.toByteArray();
Intent sendDataIntent = new Intent(MainActivity.this, SendData.class);
Bundle extras = new Bundle();
sendDataIntent.putExtras(extras);
sendDataIntent.putExtra("imageResource", imageResource);
startActivity(sendDataIntent);
}
}
I have tested the Manifest fileprover block. It seems like ok and returing path.

SetImageBitmap shows white blank full screen

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");

Proper way to instantiate an activity for use in a BitmapFactory decodestream?

I have an activity where I want the user to press a view and take a picture several places and theyre then inserted for each place he "presses". Like a photo folder.
So I have made a class to handle taking a picture and making a bitmap.
But I cannot figure out how to decode the bitmap in the activity I need it, I just get a static cannot be referenced from non-static error, because Im not instantiating it properly I guess.
Heres my approach:
case R.id.pButton2:
new CameraActivity();
Bitmap bitmap = BitmapFactory.decodeStream(CameraActivity.openFileInput("myImage"));
mImageView = (ImageView)findViewById(R.id.imageView2);
mImageView.setImageBitmap(bitmap);
mImageView.setRotation(180);
mImageView.setVisibility(View.VISIBLE);
break;
Calling this class:
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;
}
#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));
createImageFromBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String createImageFromBitmap(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;
}
}
Im using a sample from this; how do you pass images (bitmaps) between android activities using bundles?
Delete new CameraActivity().
Most likely, you can then replace:
Bitmap bitmap = BitmapFactory.decodeStream(CameraActivity.openFileInput("myImage"));
with:
Bitmap bitmap = BitmapFactory.decodeStream(openFileInput("myImage"));
since this case seems to be UI code and therefore probably is in an activity already. If it is in a fragment, use getActivity().openFileInput(). If it is somewhere else use mImageView.getContext().openFileInput().

why does mediastore take the last-1th picture from the gallery

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!

Categories

Resources