onActivityResult user cancels the activity - android

I have a activity call for getting image
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
On my onActivityResult I want to handle the scenario if the user cancels the operation in between.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
//do something
}
else
Log.i("At the","selectedimagenull");
}
else
Log.i("At the","SELECT PICTURENULL");
}
}
But if the user cancels the operation nowhere am getting information. I've tried to debug but its not catching anywhere. What am doing wrong here ?

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
//do something
}
else
Log.i("At the","selectedimagenull");
}
else
Log.i("At the","SELECT PICTURENULL");
}
else
Log.i("At the","result not ok"); // User cancelled the activity
}

Related

How to select multiple images from android gallery separately

What I want to accomplish is to select a sperate image whenever I click on a separate Imageview. For example, If a click on ImageView_1 I can select one image from the gallery and if I click on Imagview_2 I can select a separate image from the gallery. I have seen there are already many answers to this question but they are all different from what is I want to do. In the previous answers, they get all the images as a list in OnActivity Results and all the images are selected at once from the gallery.
My code
Dependency Used
implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
private void ImageOnclick(){
image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Upload_New_Product.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openFileChooser();
} else {
requestStoragePermission();
}
}
});
image_profile2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(Upload_New_Product.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
openFileChooser2();
} else {
requestStoragePermission();
}
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
private void openFileChooser2() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST2);
}
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
.start(this);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
if (Build.VERSION.SDK_INT >= 29) {
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(), resultUri));
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Use older version
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
}
//setImage_profile();
resized = Bitmap.createScaledBitmap(bitmap, 600, 600, true);
image_profile.setImageBitmap(resized);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
// UploadingImage();
// UploadingThumbnailImage();
if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null) {
ImageUri2 = data.getData();
CropImage.activity(ImageUri2)
.setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
.start(this);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri2 = result.getUri();
if (Build.VERSION.SDK_INT >= 29) {
try {
bitmap2 = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(), resultUri2));
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Use older version
try {
bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri2);
} catch (IOException e) {
e.printStackTrace();
}
}
resized2 = Bitmap.createScaledBitmap(bitmap2, 600, 600, true);
image_profile2.setImageBitmap(resized2);
//setImage_profile2();
// UploadingImage();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
You missed this line:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
And activity result should be like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST) {
if(resultCode == Activity.RESULT_OK) {
if(data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();
//TODO: do something; here is your selected images
}
} else if(data.getData() != null) {
String imagePath = data.getData().getPath();
//TODO: do something
}
}
}
Intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select images"), PICK_IMAGE_REQUEST);

No callback for startActivityForResult in case of MediaStore.INTENT_ACTION_VIDEO_CAMERA

The case is when user selects camera, he has the flexibility to either capture image or record video and the user shall be able to show the same in one's app.
For this case, MediaStore.INTENT_ACTION_VIDEO_CAMERA intent is used but no callback comes in either case of capturing image or recording video.
Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA);
startActivityForResult(intent, VIDEO_CAMERA);
For getting result, code used as follows:-
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
if (resultCode == RESULT_OK) {
if (requestCode == VIDEO_CAMERA) {
Uri uri = data.getData();
}
}
}
To start the camera and get the result back in onActivityResult(), you should create an Intent with MediaStore.ACTION_IMAGE_CAPTURE:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Similarly, to capture a video, use MediaStore.ACTION_VIDEO_CAPTURE
I finally found a solution and it is as follows:-
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
Intent chooserIntent = Intent.createChooser(takePictureIntent, "Capture Image or Video");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takeVideoIntent});
startActivityForResult(chooserIntent,VIDEO_CAMERA);
And finally receives the callback in onActivityResult and I got the uri in this way:-
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
if (resultCode == RESULT_OK) {
if (requestCode == VIDEO_CAMERA) {
Uri uri;
if (data == null || data.getData() == null) {
Bitmap bitmap (Bitmap)data.getExtras().get("data");
// TODO:Get uri from bitmap for image
uri = getImageUri(context, bitmap);
} else {
//Get uri for video
uri = data.getData();
}
}
}
}

CropActivity is not starting in onActivityResult inside Fragment

I am calling an intent to select an image and later to crop the image into aspect ratio(1,1), but when i run the app the gallery is opening but when i select the image it closes and gets back to the Fragment.
Below is the code of my Button's on click listener
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,
"SELECT IMAGE"), GALLERY_PICK);
}
});
this is the code for onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.setMinCropWindowSize(500, 500)
.start(getActivity());
Toast.makeText(SettingsActivity.this, imageUri,
Toast.LENGTH_LONG).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
Exception error = result.getError();
}
}
}
Crop activity is not starting and the app goes back to the fragment screen when i select the pic
Below is the code of MainActivity where i have used bottom navigation view and used OnActivity result as well
private void showPlacePicker() {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (Exception e) {
Log.e(TAG, e.getStackTrace().toString());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
----code---
}
}
I have used this library in one of my projects and in that I didn't explicitly create a image picker but instead let the library handle it for me. To do this,
in your code
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setAspectRatio(1, 1)
.setMinCropWindowSize(500, 500)
.start(getContext());
}
});
Handle the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
//handle the image
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//handle error
} else if(resultCode == RESULT_CANCELED){
//handle cancel case
}
}
}
For more information
In case of using appcompact fragment we cannot use .start(getActivity()) to start the crop activity.
Instead of this use:
.start(getContext(), this)
Here is code look like in fragments:
CropImage.activity(uri).setGuidelines(CropImageView.Guidelines.ON).start(getContext(), this);
ActivityResult is more suitable :
#Override
public void onActivityResult(ActivityResult activityResult) {
if (activityResult.getResultCode() == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(activityResult.getData());
}
if (activityResult.getResultCode() == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (activityResult.getResultCode() == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}

Android 7 (api 24) OnActivityResult from gallery, I can not intent to another class

I know with Android 7 you can't pass File// but in this case I'm not doing that. For testing purposes, when a user selects a file, I just want to intent to another class. When I click a video, the app just stops responding so there isn't a crash log or anything. This is my onActivityResult method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
Uri selectedImageUri = data.getData();
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
Log.d(TAG, "THE PATHHHHHHHHH " + selectedImagePath);
Intent intent = new Intent(getActivity().getApplicationContext(),
GalleryUpload.class);
// intent.putExtra("path", selectedImagePath);
startActivity(intent);
}
}
}
}
Replace all of that with:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
Uri selectedImageUri = data.getData();
Intent intent=new Intent(getActivity(), GalleryUpload.class)
.setData(selectedImageUri)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
}
}
This correctly handles both file and content Uri schemes, including passing along read access to GalleryUpload.
GalleryUpload can then use getIntent().getData() to retrieve the Uri, then use ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri.

Image-Crop-Activity doesn't send Image-Uri to receiving Activity (Android-Image-Cropper)

I am trying to crop an image (which I've chosen from the gallery or taken from my camera) and pass it to another activity which should upload the image to my firebase storage.
At first (without the image cropping) everything went well. I was able to pass and upload the image...but after adding the image-crop-code to my onActivityResult it just closes the imageCropActivity after pressing 'crop' and jumps back to my MainActivity.
I've tried but I really cannnot figure out why it does that. Maybe I'm missing something out. Any ideas?
For the image cropping I'm using this libary: https://github.com/ArthurHub/Android-Image-Cropper
Main Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mImageUri_gallery = data.getData();
mImageUri_camera = data.getData();
if (requestCode == 100 && resultCode == RESULT_OK) {
CropImage.activity(mImageUri_gallery)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUriGallery = result.getUri();
Intent intentGallery = new Intent(MainActivity.this, ImagePostActivity.class);
intentGallery.putExtra("image-uri", resultUriGallery.toString());
startActivity(intentGallery);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
} else if (resultCode != RESULT_CANCELED && data != null) {
if (requestCode == 200 && resultCode == RESULT_OK) {
CropImage.activity(mImageUri_camera)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUriCamera = result.getUri();
Intent intentCamera = new Intent(MainActivity.this, ImagePostActivity.class);
intentCamera.putExtra("image-uri", resultUriCamera.toString());
startActivity(intentCamera);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
}
ImagePostActivity
public class ImagePostActivity extends AppCompatActivity {
public static TextView txt_btn_post;
public static EditText mPostTitle;
public static ImageView imagePostPreview;
private StorageReference mStorage;
private DatabaseReference mDatabase;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_post);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Test_Stream_Uploads");
mProgress = new ProgressDialog(this);
// mPostTitle = (EditText) findViewById(R.id.mPostTitle);
imagePostPreview = (ImageView) findViewById(R.id.imagePostPreview);
Intent intent = getIntent();
mImageUri_gallery = Uri.parse(intent.getStringExtra("image-uri"));
imagePostPreview.setImageURI(mImageUri_gallery);
mImageUri_camera = Uri.parse(intent.getStringExtra("image-uri"));
imagePostPreview.setImageURI(mImageUri_camera);
txt_btn_post = (TextView) findViewById(R.id.txt_btn_post);
txt_btn_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Bild wird hochgeladen...");
mProgress.show();
if (mImageUri_gallery != null) {
StorageReference filepath = mStorage.child("Stream_Image").child(mImageUri_gallery.getLastPathSegment());
filepath.putFile(mImageUri_gallery).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Intent intent = new Intent(getBaseContext(), MainActivity.class);
DatabaseReference newPost = mDatabase.push();
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(intent);
}
});
}
}
}
I'm also actively using this tool and I actually didn't really got into your code but I can offer you an example of how it works for me. If you look into it you can easily follow and get the idea. It works for the images you take from the gallery.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(144,81)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
ib_image.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
If you want to apply this to the image you just took from the camera, you'll need to create your own uri, it's a bit long way but it's explained in the Android Documentation:(https://developer.android.com/training/camera/photobasics.html#TaskPhotoView), this I've explained in a discussion here: Image capture with camera & upload to Firebase (Uri in onActivityResult() is null)

Categories

Resources