I am trying to test the sample code related to capturing an image via camera. The documentation says that a URI can be passed as an extra in the intent were the camera will save the image.
I tried the following :
// image1 doesn't exist
File file = new File(getFilesDir() + "/image1");
Uri uri = Uri.fromFile(file);
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
if (i.resolveActivity(getPackageManager()) != null) {
startActivityForResult(i, 1337);
}
I am trying to place the image as a file named image1 in my files directory. I am testing this on the genymotion VM. I have tested getting the image as a bitmap in the return Intent, but when I use the above approach, the camera app gets stuck when I click done after taking the picture.
I'm guessing it has something to do with URI permissions. Do I need to add some permissions in the intent like in data sharing ?
Edit:
I tried to follow these instructions, except I want to save the photo in my app's directory, so I tried the following but it doesn't work (the app has camera permission) :
String imagePath = null;
try {
File image = File.createTempFile("testImage", ".jpg", getFilesDir());
imagePath = "file://" + image.getAbsolutePath();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
File file = new File(imagePath);
Uri uri = Uri.fromFile(file);
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
if (i.resolveActivity(getPackageManager()) != null) {
startActivityForResult(i, 1337);
}
I also have onActivityResult(), but its no use, as the camera app gets stuck as explained above.
Also, an additional question : When I don't have camera permission in my test app, I can still invoke the camera and the get the bitmap in intent extra, how so ? Is this something specific to genymotion VM ?
Make sure you have these permissions for your manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Everything looks good to me. Do you have onActivityResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
Related
I'm developing an Android App that uses an Intent to open the in-built camera, and take a photo that then should be saved to storage and be sent to a different intent that crops it.
I've run the app a few times but can't see any of the photos being saved anywhere in storage. I started debugging the code and found that it was skipping out on the commands in the OnActivityResult method because the resultCode parameter was always going back as 0.
Out of curiosity I manually changed this to the required value of -1, and the code then skipped out on the next if statement because data.getExtras() (data being the Intent parameter) was returning null, even though I had been adding an extra in the code that triggered the Camera Activity.
I can't quite figure out what's happening here. I'd assume the image is saving somehow because no exception is being thrown, but don't see what might be causing the empty values of resultCode and data.
My code is shown below. If anyone can give me a point in the right direction, that would be a massive help!
Thanks,
Mark
public void onClick(DialogInterface dialogInterface, int i) {
if (optionItems[i].equals(OPTION_CAMERA)) {
//intent to open device camera
Intent cameraIntent =
new Intent(
MediaStore.ACTION_IMAGE_CAPTURE
);
//create 'Spond' folder inside photo directory
//target folder for image to be saved
File imagesFolder =
new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
getString(R.string.app_name)
);
//create directory if it doesn't already exist
imagesFolder.mkdirs(); //bool return value not needed
//create file with unique id
File image = createFileAtUniquePath(imagesFolder);
//use authority for AndroidManifest to create permission
//to get uri from temporary file in app
String fileProviderAuthority = getApplicationContext().getPackageName() +
getString(R.string.authorities_fileprovider);
Uri uriSavedImage = FileProvider.getUriForFile(
getApplicationContext(),
fileProviderAuthority,
image
);
//pass URI to intent so it will be available in activity result
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//grant read/write permissions with file
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(cameraIntent, REQUEST_CAMERA);
The OnActivityResult code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
if (data.getExtras() != null) {
newAccountPhotoUri = (Uri) data.getExtras().get(MediaStore.EXTRA_OUTPUT);
newAccountPhotoFileName = getFileNameFromURI(newAccountPhotoUri);
if (!newAccountPhotoFileName.equals("")) {
appAccountPhotoChanged = true;
//send image to be cropped
cropImage(newAccountPhotoUri);
}
}
}
//...
}
I'm trying to open my photo with intent to view it in my phone's default gallery app, but when I do so, my app flashes and reloads without providing any errors. I'm trying to open my photo like this:
Uri uri = FileProvider.getUriForFile(context, "www.markwen.space.fileprovider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/jpg");
startActivity(intent);
I cannot find anything wrong in here. I'm thinking if it would be when I save my photo, which is taken using the camera, I didn't encode it correctly. When I save my photo, I simply follow the instructions here: https://developer.android.com/training/camera/photobasics.html
So how do you guys save your photo after you take the photo with your phone's camera app? What can I do to open up my photo? Thanks
Update:
here is how I take the photo:
private void startPhotoIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Create photo file
File photo = new File(getFileDirectory(".jpg"));
// Save intent result to the file
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), "www.markwen.space.fileprovider", photo));
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Start intent to take the picture
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
here is the way I am saving the photos I took:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Photo
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == -1) {
Uri imageUrl = data.getData();
if (imageUrl != null) {
// Announce picture to let other photo galleries to update
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imageUrl);
getActivity().sendBroadcast(mediaScanIntent);
try {
MediaStore.Images.Media.insertImage(getContext().getContentResolver(), directory + filename, "Multimedia-Image", "Multimedia-Image");
Toast.makeText(getContext(), "Image saved to gallery", Toast.LENGTH_LONG).show();
filename = "";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
Get the absolut path of your image
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(file.getAbsolutePath())));
i'm not sure what your trying to do,
saving the picture to the phone is easy,
deepending on what intent you are using.
i would look for a way to change the intent so to specify the saving location for the image itself
Google for EXTRA_STREAM EXTRA_OUTPUT
I am using an implicit Intent to take a picture. I have been following the work outlined in this tutorial. The issue that I am having is that the extra added to the Intent is not being delivered. Here is the code I'm using:
private void dispatchTakePictureIntent(Context context) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile(this.getActivity());
} catch (IOException ex) {
Log.e(TAG, "Error creating file: " + ex.toString());
//TODO: 2017/1/24 - Handle file not created
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Error")
.setMessage(ex.toString());
final AlertDialog dialog = builder.create();
dialog.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.myapp",
photoFile);
//THIS EXTRA IS NOT BEING ADDED TO THE INTENT
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
galleryAddPic(context, photoFile.getAbsolutePath());
}
}
}
When the onActivityResult method is fired, the Intent is empty. Here is that code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
//These extras are empty. I have used the debug tool, and there is nothing in here.
Bundle extras = data.getExtras();
//extras is null
imageBitmap = (Bitmap) extras.get("data");
previewImage.setImageBitmap(imageBitmap);
}
}
Why is the intent empty? What do I need to do to fix this issue?
Why is the intent empty?
Because you asked for it to be empty, by including EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE request. Quoting the documentation:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT.
What do I need to do to fix this issue?
Either:
Get rid of EXTRA_OUTPUT (if you want a thumbnail-sized image), or
Stop looking for the "data" extra, and look in the location that you specified in EXTRA_OUTPUT
I am developing android app and my app have button to take camera. Previously i had fallen into a state where return data in onActivityResult after taking picture being null. This is camera expected behaviour whereby if we put EXTRA_OUTPUT in intent , it would return null. For that reason , I did null checking code and it went fine .
Now again after a few days and i tested . I still fallen into same issue again. But this time data is not null. data has empty intent such as intent and data.getData() become null.I fixed this by checking data.getData() == null and it works again. I don't why it is like that. Just curious about what was going on. For that reason i have to re-upload to production again. :-(
//camera intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra("requestCode", Constants.REQUEST_IMAGE_CAPTURE);
Intent chooseImageIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
chooseImageIntent.setType("image/* video/*");
chooseImageIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
chooseImageIntent.putExtra("requestCode", Constants.REQUEST_CHOOSE_FROM);
//app can use camera
if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
//add output file path which camera will save image to
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Helpers.getOutputMediaFileUri());
//create choose
Intent chooser = Intent.createChooser(chooseImageIntent, "Select From");
//add take camera intent as first intent
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS,new Intent[]{takePictureIntent});
//open up dialog
((Activity) mContext).startActivityForResult(chooser, Constants.REQUEST_CHOOSE_FROM);
} else {
((Activity) mContext).startActivityForResult(chooseImageIntent, Constants.REQUEST_IMAGE_GALLERY);
}
EDITED
I know I how to fix the problem. What i don't understand is return data must be null if i put in EXTRA_OUTPUT. Mostly importantly the code I implemented few weeks back , i am quite sure that data return null and suddenly it is non null value again.
Actually the camera intent doesnot return the data in intent because after getting image it kill the activity.
so try this
void opencameraForPicture(int requestCode, Uri fileUri) {
checkPermissionForMarshMello(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE);
Intent intent = new Intent(Constants.CAMERA_INTERNAL_CLASS);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
/* start activity for result pass intent as argument and request code */
startActivityForResult(intent, requestCode);
}
/**
* This method set the path for the captured image from camera for adding
* the new picture in the list
*/
private Uri getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "."
+ Constants.CONTAINER);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + System.currentTimeMillis() + ".png");
Uri uri = null;
if (mediaFile != null) {
uri = Uri.fromFile(mediaFile);
}
return uri;
}
in #Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String imagePath = fileUri.getPath();
//you can decode this path as bitmap
}
I am trying to include a camera in my app that saves the files locally on the SD card. The camera application starts, but the resultCode is always 0. I have added the following permissions to my Manifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here is the code for my the camera:
#SuppressLint("SimpleDateFormat")
private void takePicture(){
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/resources/resources/WI1");
SimpleDateFormat timeStampFormat = new SimpleDateFormat("MM/dd/yyyy");
String image_name =username +"-"+ timeStampFormat.format(new Date())+".png";
File image = new File(imagesFolder, image_name);
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
int request_code = 100;
startActivityForResult(imageIntent, request_code);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this,"Error Saving Image, please throw device at wall", Toast.LENGTH_SHORT).show();
} // end on activity result
What's causing the bug?
Thanks!
EDIT: I removed the previously posted logcat information, as it was not relevant to this issue.
EDIT2:
I half solved the issue, if I use this code the camera works just fine. Could someone tell me what would cause that?
private void takePicture(){
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/resources/resources/WI1");
String image_name = "matt"+image_count+".png";
image_count+=1; // this is at the moment useless.
File image = new File(imagesFolder, image_name);
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
int request_code = 100;
startActivityForResult(imageIntent, request_code);
}
EDIT 3:
The issue is with the timeStampFormat, if I exclude it the camera works just fine. Could someone explain why? If I'm not mistaken, it's because the date format I chose has forward slashes in it.
I was having this same error - resultCode was always 0. Turns out that after I took the picture in the camera app, I was clicking the X on the bottom right instead of the checkmark in the bottom center.
it is coming 0 because you have not set result code in the activity , suppose if i call activity b from a .. and on activity b i set setReuslt(reuslt_ok) , then only onactivity result will get the result code as result_ok.. by default the result code is 0
since you are opening the internal camera activity of android , so you are not setting your result code there, so when camera activity finishes it returns the default code back to you