I'm trying to save an image from the camera of the phone and then retrieve it to save it on firebase storage.
I tryed a lot of ways of doing it, but I always get a null when I retrieve it.
Here it is how I make the picture with the camera:
private void camera() {
if (ActivityCompat.checkSelfPermission(MainChatActivity.this,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, PHOTO_CAMERA_IMAGE);
}
}
Here I save it on the phone:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (data != null)
uploadImage(data.getData());
break;
case PHOTO_CAMERA_IMAGE:
if (resultCode == RESULT_OK) {
if (data != null) {
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();
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"borealos.com.chat.fileprovider",
photoFile);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, photoURI));
takePictureIntent.putExtra("foto", photoURI);
Uri uri = (Uri) takePictureIntent.getExtras().get(MediaStore.EXTRA_OUTPUT);
uploadImage(photoURI);
// startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
} catch (IOException ex) {
// Error occurred while creating the Fil
}
}
}
}
break;
}}
And here I retrieve it for uploading on firebase:
private void uploadImage( final Uri filePath) {
Uri filePath2=filePath;
final String s;
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
s = UUID.randomUUID().toString();
ref = storageReference.child("images/" + s);
ref.putFile(filePath)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
sendImage(filePath, task.getResult().getDownloadUrl().toString());
}
}
});
}
}
Thanks for the help in advice
Related
I have a question about upload image to firebase and it works before and after I done other activity...It failed...Can your guys help me...
The main error was when user click OK or CANCEL in confirmation page, the app crash. App will crash too when user select from gallery...
Here is the logcat...
2021-03-30 22:56:16.853 12576-12576/? E/in.firebasetes: Unknown bits set in runtime_flags: 0x8000
And here is the code for activity...
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users");
userID = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference();
UserPic = (ImageView) findViewById(R.id.UserPic);
UserPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VerifyPermission();
}
if (user != null){
if (user.getPhotoUrl() != null) {
Glide.with(this).load(user.getPhotoUrl()).into(UserPic);
}
}
}
private void VerifyPermission() {
if (ContextCompat.checkSelfPermission(UserProfile.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UserProfile.this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
}else {
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
selectOptionList();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
selectOptionList();
}else {
Toast.makeText(UserProfile.this, "Camera Permissions is required", Toast.LENGTH_LONG).show();
}
}
}
private void selectOptionList(){
selectList = getResources().getStringArray(R.array.selectList);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an option");
builder.setItems(selectList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
dispatchTakePictureIntent();
break;
case 1:
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY_REQUEST_CODE);
break;
case 2:
dialog.dismiss();
break;
}
}
});
alertDialog = builder.create();
builder.show();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, "interpayment.main.firebasetest.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + userID + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
Toast.makeText(UserProfile.this, "Opening Camera", Toast.LENGTH_SHORT).show();
return image;
}
private void uploadImageToFirebase(String name, Uri contentUri) {
final StorageReference img = storageReference.child("pictures/" + name);
img.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
img.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d("100", "onSuccess: Upload Image URL is " + uri);
Toast.makeText(UserProfile.this, "Uploaded", Toast.LENGTH_SHORT).show();
setUserProfileUrl(uri);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void setUserProfileUrl(Uri uri) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest request = new UserProfileChangeRequest.Builder().setPhotoUri(uri).build();
user.updateProfile(request).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(UserProfile.this, "Updated", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserProfile.this, "Failed set Profile", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE) {
File f = new File(currentPhotoPath);
UserPic.setImageURI(Uri.fromFile(f));
Log.d("tag", "Absolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
uploadImageToFirebase(f.getName(), contentUri);
}else if(requestCode == GALLERY_REQUEST_CODE && data != null){
Uri img = data.getData();
Log.d("tag", "onActivityResult: Gallery Image Uri: " + img);
UserPic.setImageURI(img);
uploadImageToFirebase(currentPhotoPath, img);
}
}
}
I appreciate for your guys helping and thanks a lot for taking time to help me. Logcat was like this...
Logcat
----------------------------------------------------------------------
Update
My question is solved. The problem was the onStop function, I removed it. This is because the system set the [open camera] and [take photo from gallery] as new actitvity. So, if you have the onStop function, system close the apps when you open camera or others. This cause the apps automatically close and no any error in logcat.
I have a project witch have permission to camera and storage.
When the user click in some buttons the camera will be open by intent and take picture then saved it in the device to add it to firebase storage.
This operation was successful on most devices, but in Redmi A8(Android 10 , MIUI 12.0.1) it
was failed , the camera open then the application stop , maybe it failed to save the picture or failed to get it in ActicityResult.
Who I can solve it ?
Note: This is a part of methods in my code.
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(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.apps.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
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,
".jpg",
storageDir
);
currentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
File f = new File(currentPhotoPath);
//showImage.setImageURI(Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
uploadImageToFirebase(f.getName(), contentUri);
}
}
}
private void uploadImageToFirebase(String name, Uri contentUri) {
final StorageReference image = storageReference.child("pictures/" + name);
image.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
image.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().child("Shifts").child(empId+"").
child(shiftKey).child(shiftImageType).setValue(uri+"");
alertDialog.dismiss();
}
});
startActivity(new Intent(getActivity() , MainActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage()+"", Toast.LENGTH_SHORT).show();
}
});
}
I have no experience in coding and i am just creating a app from tutorials in android studio. I have come a very long way in creating the app. I have implemented the code for selecting a image from the devive gallery and now i wonder how i can set that picture as a Firebase PhotoURL for the current user?
I have implemented that while I was trying firebase. Hope this would do your work.
getImageFromMobile is set to the onClick Method of ImageButton which I am using to set Image to.
public void getImageFromMobile(View view) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(intent , galleryRequestCode);
}
private void postDataToFirebase() {
mProgressDialog.setMessage("Posting the Blog to Firebase");
mProgressDialog.setCancelable(false);
final String titleValue = mPostTitle.getText().toString();
final String description = mPostDescription.getText().toString();
if((!TextUtils.isEmpty(titleValue))&& (!TextUtils.isEmpty(description)) && bitmap != null)
{
mProgressDialog.show();
StorageReference filePath = mStorage.child("Blog_Images").child(imagePathName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(PostActivity.this.getContentResolver(), bitmap, imagePathName, null);
Uri uri = Uri.parse(path);
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabaseReference.push();
newPost.child("Title").setValue(titleValue);
newPost.child("Desc").setValue(description);
newPost.child("imageUrl").setValue(downloadUrl.toString());
Toast.makeText(PostActivity.this, "Data Posted Successfully to Firebase server", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
Intent intent = new Intent(PostActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == galleryRequestCode && resultCode == RESULT_OK){
Uri imageUri = data.getData();
imagePathName = imageUri.getLastPathSegment();
Log.i("ImagePathName",imagePathName);
Toast.makeText(this, "ImagePathNameto be Checked" + imagePathName, Toast.LENGTH_SHORT).show();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageButton.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent in an onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.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
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support 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 = 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 = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
#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));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.
I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
#Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
#Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
Call the camera through intent, capture images, and save it locally in the gallery.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);
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));.