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
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 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 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
In my app I am trying to set an ImageView's image to an image that was just taken with the camera. My problem is that it works on my old Droid (Android 2.2), but not on my Droid Razr (Android 4.0). I was wondering if anyone could help me figure out why.
Here is the camera Intent when the Take Photo button is clicked:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String imageFileName = System.currentTimeMillis() + ".jpg";
File photo = new File(Environment.getExternalStorageDirectory(),
imageFileName);
imageUri = Uri.fromFile(photo);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, ACTIVITY_CAMERA);
Here is the Activity's result:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_CAMERA) {
if(resultCode == Activity.RESULT_OK){
imageView.setImageUri(imageUri);
}
}
}
The ImageView remains blank on the Razr.
Weird how looking at the logcat is helpful.
Anyway, I was getting "bitmap is too large" when trying to set the ImageView's image. Even before this issue I tried Google's solution here. However, the bitmap is always null and I haven't looked into it enough to figure out why.
EDIT: I got Google's solution to work. For the decodeFile() method, I was passing in my Uri as a string: imageUri.toString(). I changed this to imageUri.getPath() and it is now working.
I use following code take a Picture from camera and to obtain picture's path.
...
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_IMAGE_CAPTURE); // image capture
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + resultCode + " request:" + requestCode);
switch (requestCode) {
case CAMERA_IMAGE_CAPTURE:
Uri selectedImageUri = data.getData();
userImagePath = getPath(selectedImageUri);
break;
}
}
It works good on emulator and on different devices. But on Samsung Galaxy Nexus(4.0.2) it does not launches Camera app. But it returns RESULT_OK to onActivityResult and I see no exceptions in LogCat.
Please give me and advice how to solve this issue.
Thanks in advance!
You are missing EXTRA_OUTPUT, which may impact matters. My Galaxy Nexus can run this sample project successfully, which uses the following code to request the picture:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output = new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);