Capturing image from gallery & camera in android - android

First thing I know this is repeated question but I don't have problem in capturing image from gallery or camera. I created on dummy project to check my code here it's working fine
But when I used same code in my project & here it's not working even I didn't get any error
as soon as I start activity for result it get cancelled but still I can see images from gallery & I can capture image from camera.
When I checked logcat I found following warning don't know why it's coming & how I can fix this thing
W/NetworkConnectivityListener(2399): onReceived() called with CONNECTED and Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000000 (has extras) }
Edit:-- Added Code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, PICK_Camera_IMAGE);
return true;
case R.id.gallery:
try {
Intent gintent = new Intent();
gintent.setType("image/*");
gintent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gintent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return true;
}
return false;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
Toast.makeText(this, "Picture was taken", Toast.LENGTH_SHORT).show();
Uri selectedImageUri = imageUri;
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
} 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();
}
break;
}
}
Thank You

Take a look at LinderdaumEngineActivity.java from my project Linderdaum Engine:
Capture image from camera:
public void CapturePhoto( String FileName )
{
try
{
File f = new File(FileName);
if ( f.exists() && f.canWrite() ) f.delete();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,Uri.fromFile(f));
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No camera: " + e );
}
catch ( Exception e )
{
Log.e( TAG, "Cannot make photo: " + e );
}
}
Open image from gallery:
public static void OpenImage()
{
try
{
Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
intent.setType( "image/*" );
startActivityForResult( intent, SELECT_PICTURE_CALLBACK );
}
catch ( ActivityNotFoundException e )
{
Log.e( TAG, "No gallery: " + e );
}
}
Also, do not forget to add permissions to your manifest:
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-permission android:name="android.permission.CAMERA" android:required="false"/>

Please check your AndroidManifest, make sure you have all the right permissions.

See official documentation with file provider for above android 7
getUriForFile(Context, String, File) which returns a content:// URI. For
more recent apps targeting Android 7.0 (API level 24) and higher, passing a
file:// URI across a package boundary causes a FileUriExposedException.
Therefore, we now present a more generic way of storing images using a
FileProvider.
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
Official doc

Related

Android 11 scooped storage manage_external_storage permission is not accepted by google play console

my app is working fine below the 10 version but android 11 and higher versions do not support external storage. my picker is not picking any document file. but after giving manage_external_storage permission in manifest google play store did not approve my app. please help if you know any alternate solution for all file access permission.
Try like below. Create global variable as needed or refactor as per your need. This is tested upto Android 11.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private void OpenCamera() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createFile();
} catch (Exception ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getApplicationContext().getPackageName() + ".fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 3);
}
// }
} catch (Exception e) {
}
}
private File createFile() 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
ImageLoc = image.getAbsolutePath();
return image;
}
// Open Gallery
private void OpenGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 1);
}
// onActivityResult handles gallery pics, camera pics and pdf.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
if (data.getData() != null) {
try {
Uri imageUri = data.getData();
File file = new File(Path_from_Uri.getPath(getActivity(), imageUri));
} catch (Exception e) {
Toast.makeText(getActivity(), "Please Select Image from Gallery", Toast.LENGTH_LONG).show();
}
}
}
} else if (requestCode == 3) {
try {
File file = new File(ImageLoc);
} catch (Exception e) {
Log.d("TAG", e.toString());
}
}
}

How to make my share intent support whatsapp and google+

I am using this code to share an image:
File file = ImageLoader.getInstance().getDiskCache().get(imageUrl);
if (file != null && file.exists()) {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(Intent.createChooser(intent, "Send"));
} else {
Toast.makeText(context, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
I used UIL to load the image previously, so mageLoader.getInstance().getDiskCache().get(imageUrl); returns the image file from disk cache.
Gmail, Hangouts, Messages, Drive etc can grab the file but on Google+, the grabbed is not gotten while Whatsapp says "This format is not supported". However if I save the file to Downloads folder and share via Gallery app, the same image is picked by both Google+ and Whatsapp.
You can try to save the file to the external cache, it's working for me. Example with Glide:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/*");
Glide.with(getContext())
.load("http://...url.here...")
.asBitmap()
.into(new SimpleTarget<Bitmap>(500, 500) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
try {
File file = new File(getContext().getExternalCacheDir(), "file_to_share.png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getContext().startActivity(Intent.createChooser(sendIntent, ""));
} catch (IOException e) {
Log.e("Share", e.getMessage(), e);
} finally {
}
}
});
In case you're using Universal Image Loader, I applied the accepted answer to save the image and delete it as soon as the user returns from sharing:
private File saveImage(String imageUri, String fileName) {
File file = new File(this.getExternalCacheDir(), fileName);
InputStream sourceStream = null;
File cachedImage = ImageLoader.getInstance().getDiskCache().get(imageUri);
if (cachedImage != null && cachedImage.exists()) {
Log.d(TAG, "Cache exists");
try {
sourceStream = new FileInputStream(cachedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Cache doesn't exist");
}
if (sourceStream != null) {
Log.d(TAG, "SourceStream is not null");
try {
OutputStream targetStram = new FileOutputStream(file);
try {
try {
IoUtils.copyStream(sourceStream, targetStram, null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
targetStram.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
sourceStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.d(TAG, "SourceStream is null");
Toast.makeText(this, "Image cannot be shared", Toast.LENGTH_SHORT).show();
}
return file;
}
private void shareImage(String imageUrl, String fileName) {
if (isSDReadableWritable()) {
file = saveImage(imageUrl, fileName);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(Intent.createChooser(intent, "Send"), 20);
} else {
Toast.makeText(this, "Storage cannot be accessed", Toast.LENGTH_SHORT).show();
}
}
To delete the file just override onActivityResult and it'll be deleted immediately after sharing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20 && file != null) {
boolean isDelete = file.delete();
Log.d(TAG, "isDelete is " + isDelete);
}
}

Android file.canRead() = false when choosing image but not when TAKING photo

I have 2 buttons on an "upload image" page for users to upload an image to a web service. One is for selecting an image that is on your device, the other for taking a photo with your camera.
thisFragment.findViewById(R.id.btnChooseImage).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Assert.assertNotNull("file uri not null before firing intent", mFileUri);
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//this is the file that the camera app will write to
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
thisFragment.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Assert.assertNotNull("file uri not null before firing intent", mFileUri);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//this is the file that the camera app will write to
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
btnTakePhoto works fine when it loads an ImageView with the result when I TAKE a photo, but when I CHOOSE a photo using the other button the imageView is blank...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null) {
if(data.getData() != null) {
Log.v(LOG_TAG, "intent data: " + data.getData().toString());
}
if(data.getAction() != null) {
Log.v(LOG_TAG, "intent action: " + data.getAction().toString());
}
if(data.getExtras() != null) {
Log.v(LOG_TAG, "intent extras: " + data.getExtras().toString());
}
}
Assert.assertNotNull("file uri in onActivityResult", mFileUri);
Log.v(LOG_TAG, "stored file name is " + mFileUri.toString());
File file = getFileFromUri();
if(file != null) {
Bitmap bm = decodeSampledBitmapFromFile(file, 500, 500);
imgMain.setImageBitmap(bm);
}else{
imgMain.setImageBitmap(null);
}
} else {
parentActivity.finish();
}
}
private File getFileFromUri() {
if(mFileUri != null) {
try {
URI uri;
if(mFileUri.toString().startsWith("file://")){
//normal path
uri = URI.create(mFileUri.toString());
} else {
//support path
uri = URI.create("file://" + mFileUri.toString());
}
File file = new File(uri);
if (file != null) {
//if (file.canRead()) {
return file;
//}
}
} catch (Exception e) {
return null;
}
}
return null;
}
I noticed that when I hit this line of code:
if (file.canRead()) {
return file;
}
file.canRead() is TRUE when I take a picture, but FALSE when I CHOOSE a picture. When I step through and look at the value of the "uri" variable, here they are:
file:///storage/emulated/0/Pictures/IMG_20150916_141518.jpg - this works
file:///storage/emulated/0/Pictures/IMG_20150916_141854.jpg - this doesn't work
any idea what's going on here?
UPDATE: tried using the InputStream approach from ContentResolver, but the bitmap still can't be displayed:
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = parentActivity.getContentResolver().openInputStream(selectedImage);
}catch (FileNotFoundException e){
Log.v(LOG_TAG, "cant load file " + mFileUri.toString());
}
Bitmap bm = BitmapFactory.decodeStream(imageStream);
imgMain.setImageBitmap(bm);

Setting ImageView after Crop not working

I've created a basic activity with an imageView and two buttons. 1 Button opens the gallery, the other opens the camera. Both of which pass the result into a image cropping library. The cropped image is saved and shown in the imageView.
The first I do this with either button, everything works smoothly. However on the second attempt the imageView does not get replaced but the image that has been saved has changed.
So basically the imageView doesn't change to the new image if it already has the first result.
Here's Code:
public void takeDisplayPicture(View view) {
final String TAKE_DISPLAY_PICTURE = "Take Display Picture";
Log.d(TAKE_DISPLAY_PICTURE, "Clicked");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
Log.e(TAKE_DISPLAY_PICTURE, "Error Occurred");
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
Log.d(TAKE_DISPLAY_PICTURE, photoFile.getAbsolutePath());
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} else {
Log.d(TAKE_DISPLAY_PICTURE, "No Camera");
Toast.makeText(getApplicationContext(),"No Camera Available",Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
final String ON_ACTIVITY_RESULT = "On Activity Result";
Log.d(ON_ACTIVITY_RESULT, "Triggered");
Log.d(ON_ACTIVITY_RESULT, "Request Code: "+Integer.toString(requestCode)+" Result Code: "+Integer.toString(resultCode));
Uri img = Uri.parse("file:///"+Config.APP_PATH+Config.APP_USER_PATH+"/"+Config.DISPLAY_PICTURE_NAME+".png");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Log.d(ON_ACTIVITY_RESULT, "Beginning Crop");
Log.d(ON_ACTIVITY_RESULT,img.toString());
beginCrop(img, img);
} else if (requestCode == Crop.REQUEST_CROP) {
Log.d(ON_ACTIVITY_RESULT, "Handling Crop");
handleCrop(resultCode, result);
} else if (requestCode == 2){
Log.d(ON_ACTIVITY_RESULT, "Gallery Image Returned");
File file = new File(img.getPath());
file.delete();
Uri src = result.getData();
Log.d(ON_ACTIVITY_RESULT, src.toString());
beginCrop(src, img);
}
}
private void beginCrop(Uri source, Uri output){
final String BEGIN_CROP = "Begin Crop";
Log.d(BEGIN_CROP, "Beginning");
new Crop(source).output(output).asSquare().start(this);
}
private void handleCrop(int resultCode, Intent result) {
final String HANDLE_CROP = "Handle Crop";
if (resultCode == RESULT_OK) {
Log.d(HANDLE_CROP, "Set ImageView");
displayPicture.setImageURI(Crop.getOutput(result));
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Crop.getOutput(result));
} catch (Exception e ){
Log.d(HANDLE_CROP, "Error Occurred");
}
} else if (resultCode == Crop.RESULT_ERROR) {
Log.d(HANDLE_CROP, "Error Occurred");
}
}
String currentPhotoPath;
private File createImageFile() throws IOException {
final String CREATE_IMAGE_FILE = "Create Image File";
String fileName = "display_picture";
File dir = new File(Config.APP_PATH+Config.APP_USER_PATH);
dir.mkdirs();
File image = new File(dir,fileName+".png");
return image;
}
public void chooseFromGallery(View view) {
final String CHOOSE_FROM_GALLERY = "Choose From Gallery";
Log.d(CHOOSE_FROM_GALLERY, "Clicked");
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
If you read setImageURI:
if (mResource != 0 ||
(mUri != uri &&
(uri == null || mUri == null || !uri.equals(mUri)))) {
//Set URI...
}
Basically, setImageURI only works if the Uri of the image isn't equal to the Uri you want to currently set. Your button doesn't work second time because Crop.getOutput(result) returns the same Uri everytime you press the button, so setImageURI does nothing.
To solve this, you can add displayPicture.setImageURI(null); before displayPicture.setImageURI(Crop.getOutput(result));.

Taking picture with Camera Intent never get back to onActivityResult()

I have an activity which is called from a TabActivity (I know it's deprecated) as:
intent2 = new Intent().setClass(this, sin2.class);
spec = tabHost.newTabSpec("second").setIndicator("Second").setContent(intent2);
tabHost.addTab(spec);
which is an activity that takes pictures, save them and set a thumbnail. It works perfectly on a lot of devices but on Samsung Galaxy Pocket or Galaxy Wonder (always Android 2.x) sometimes when I start the Camera Intent, it never gets back to onActivityResult(), that means:
I take a picture
I save it
I doesn't get back to onActivityResult()
It allows me to take another picture
and looping... I never get back, if I press finish(), I come back to my current activity.
I've read on StackOverflow about doing stuff like getParent().startActivityForResult(Intent,RequestCode); but doesn't work.
This is how I take my pictures:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(photofile);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, num);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK)
{
if (requestCode == 1)
{
.............. things I do.
}
}
}
Thanks in advance!!
MY CODE:
on onCreate (photo is a BitMap):
scatta.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
photo = null;
if(foto1.getDrawable()==null)
foto(1);
else if(foto2.getDrawable()==null)
foto(2);
else if(foto3.getDrawable()==null)
foto(3);
else
Toast.makeText(sinistri2.this, "Cancella una foto per poter scattare un'altra", Toast.LENGTH_LONG).show();
}
});
foto(int) function:
#SuppressLint("SimpleDateFormat")
public void hacerfoto(int num){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String n = sdf.format(new Date());
String fotoname = "Immagine-"+ n +".jpg";
File photostorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File photostorage2 = new File(photostorage, "im");
photostorage2.mkdirs();
photofile = new File(photostorage2, fotoname);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(photofile);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, num);
}
my onActivityResult function:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String filename = sacarfoto();
if (requestCode == 1){
sacarfoto();
if(photo != null){
ruta1 = sacarfoto();
foto1.setBackgroundColor(Color.parseColor("#00000000"));
photo = f.resize(photo, filename);
foto1.setImageBitmap(photo);
cancellare1.setVisibility(View.VISIBLE);
}
else{
cancellare1.setVisibility(View.GONE);
foto1.setBackgroundResource(R.drawable.fondoicona);
Toast.makeText(this, "C'è stato un errore, riprova a scattare la foto", Toast.LENGTH_LONG).show();
}
try {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(ruta1);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} catch (Exception e) {
}
}
if (requestCode == 2){
sacarfoto();
if(photo != null){
ruta2 = sacarfoto();
photo = f.resize(photo, filename);
foto2.setImageBitmap(photo);
foto2.setBackgroundColor(Color.parseColor("#00000000"));
cancellare2.setVisibility(View.VISIBLE);
}
else{
cancellare2.setVisibility(View.GONE);
foto2.setBackgroundResource(R.drawable.fondoicona);
Toast.makeText(this, "C'è stato un errore, riprova a scattare la foto", Toast.LENGTH_LONG).show();
}
try{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(ruta2);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} catch (Exception e) {
}
}
if (requestCode == 3){
sacarfoto();
if(photo != null){
ruta3 = sacarfoto();
photo = f.resize(photo, filename);
foto3.setImageBitmap(photo);
foto3.setBackgroundColor(Color.parseColor("#00000000"));
cancellare3.setVisibility(View.VISIBLE);
}
else{
cancellare3.setVisibility(View.GONE);
foto3.setBackgroundResource(R.drawable.fondoicona);
Toast.makeText(this, "C'è stato un errore, riprova a scattare la foto", Toast.LENGTH_LONG).show();
}
try {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(ruta3);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} catch (Exception e) {
}
}
if (requestCode == 4) {
try{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
photo = f.decodeAndResizeFile(new File(selectedImagePath));
} catch(NullPointerException ex){
try {
photo = (Bitmap) data.getExtras().get("data");
}
catch (Exception e){
photo = BitmapFactory.decodeFile(selectedImagePath);
}
}
if(photo != null){
if (foto1.getDrawable()==null){
photo = f.resize(photo,selectedImagePath);
ruta1 = selectedImagePath;
foto1.setImageBitmap(photo);
foto1.setBackgroundColor(Color.parseColor("#00000000"));
cancellare1.setVisibility(View.VISIBLE);
}
else if (foto2.getDrawable()==null){
photo = f.resize(photo,selectedImagePath);
ruta2 = selectedImagePath;
foto2.setImageBitmap(photo);
foto2.setBackgroundColor(Color.parseColor("#00000000"));
cancellare2.setVisibility(View.VISIBLE);
}
else if (foto3.getDrawable()==null){
photo = f.resize(photo,selectedImagePath);
ruta3 = selectedImagePath;
foto3.setImageBitmap(photo);
foto3.setBackgroundColor(Color.parseColor("#00000000"));
cancellare3.setVisibility(View.VISIBLE);
}
else
Toast.makeText(sinistri2.this, "Cancella una foto per poter scattare un'altra", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Non si è potuto riuscire, riprova scattando una foto o scegliendo una foto dalla gallery.", Toast.LENGTH_LONG).show();
}
}
}
}
the function sacarfoto() gives a String but sometimes works for doing a process, but it doesn't matter in this error.
I'm pretty sure that you think that it's never returned, but in fact it's returning a RESULT_CANCEL. Try to add if(result == RESULT_CANCEL) in your onActivityResult. Maybe it was impossible for the camera to save the picture or something like that.

Categories

Resources