Capture photo intent resultCode - java

How can I detect wether the user take picture and selects it (with the confirm button on camera) or they just turn on a camera, take a picture and remove it (with the cancel button on camera)
When the user take picture I am loading that picture into an ImageView. If user hits confirm button then everything is OK but if user don't want that picture and decide to hit cancel button then the ImageView goes blank.
This is my camera intent :
void capturePhoto() {
// ImagePicker.pickImage(this, "Select your image:");
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 f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
Uri photoURI = Uri.fromFile(f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
pictureUri = null;
}
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
And onActivityResult, in both cases the resultCode is always 1. (note that RESULT_OK is -1) and I dont know why.
This is how I set image to ImageView using Glide:
Glide.with(this).load(mCurrentPhotoPath).centerCrop().into(imageView);
Any Suggestions?
Thanks!

you just need to pass if statement in onActivityresult
cause if you use directly that URI or whatever you use which has no any frame set cause user cancel it so just do as given
//if needed than
//public static final int RESULT_OK = -1;
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
//do your stuff here
}
}

You can use below code
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (isCameraPermissionEnabled()) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
1);
}
}
}
public boolean isCameraPermissionEnabled() {
return !(Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED );
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
mBitmap = (Bitmap) extras.get("data");
imageView.setBackground(new BitmapDrawable(getResources(),mBitmap));
}
}
//For more information https://developer.android.com/training/camera/photobasics.html

Related

How to get image uri from camera intent?

i am trying to get the uri of the picture that have been taken from device camera. I just tried some of the advices from online but i could not manage to solve this problem here is the my code parts.
ImageView petImage;
Uri imageData;
petImage = view.findViewById(R.id.imgPetPic);
petImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// display error state to the user
Toast.makeText(getActivity(), "Camera is Not Available", Toast.LENGTH_SHORT).show();
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
imageData = data.getData();
Bitmap bp = (Bitmap) data.getExtras().get("data");
petImage.setImageBitmap(bp);
} else if (resultCode == RESULT_CANCELED)
Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
}
}
After that code parts worked. ımageData variable is still null. How do i fix this.

Insert a picture into an imageview

In my app, I insert two pictures into two image-views and I use activity for result to fetch the photo from gallery.
private void showFileChooser () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
}
private void showFileChooser2 () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent2, "Select Picture"), PICK_IMAGE_REQUEST2);
}
});
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
rbitmap = getResizedBitmap(bitmap, 1000);//Setting the Bitmap to ImageView
imageViewUserImage.setImageBitmap(rbitmap);
imageViewUserImage.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath2 = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath2);
rbitmap2 = getResizedBitmap(bitmap2, 1000);//Setting the Bitmap to ImageView
imageViewUserImage2.setImageBitmap(rbitmap2);
imageViewUserImage2.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The app is doing well but sometimes a weird thing happens.Sometimes once I click the desired photo in gallery, the app returns to the main activity and I find the previous loaded image in the other image-view is deleted.In other words, sometimes loading a picture in one of them deletes the loaded image in the other.
That glitch doesn't happen always, it sometimes happens and sometimes the app works well without any problem.
How can I fix that?
Place a break point in the catch on the 'e.printStackTrace();' line.
Play with the app, and see the reason for failure.
Without any stack trace we can only guess the reason.
I found the problem.The size of the images are kind of large so a "memory is out" error appears.To avoid such problem, I recycled each bitmap within its if case.
private void showFileChooser () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
}
private void showFileChooser2 () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent2, "Select Picture"), PICK_IMAGE_REQUEST2);
}
});
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
rbitmap = getResizedBitmap(bitmap, 1000);//Setting the Bitmap to ImageView
imageViewUserImage.setImageBitmap(rbitmap);
bitmap.recycle;
imageViewUserImage.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath2 = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath2);
rbitmap2 = getResizedBitmap(bitmap2, 1000);//Setting the Bitmap to ImageView
imageViewUserImage2.setImageBitmap(rbitmap2);
bitmap2.recycle;
imageViewUserImage2.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Set two cropped image from camera separately in image view (Android Studio)

I am try to take two image from camera and crop image then show cropped image in two Imageview separately.
I have 2 Button to open camera one for capture first image then cropped to display it in Imageview and the second do the same thing.
My code in MainActivity
variable in calss
static int CAMERA_REQUEST_CODE = 228;
static int CAMERA_REQUEST_CODE1 = 229;
Uri pictureUri = null;
ImageView iv, iv1;
Button bt, bt1;
onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv);
bt = findViewById(R.id.bt);
iv1 = findViewById(R.id.iv1);
bt1 = findViewById(R.id.bt1);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera1();
}
});
}
invokeCamera() and invokeCamera1() function
public void invokeCamera() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public void invokeCamera1() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE1);
}
createImageFile() function
// To create image file in pictures directory
public File createImageFile() {
// the public picture director
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // To get pictures directory from android system
// timestamp makes unique name.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
// put together the directory and the timestamp to make a unique image location.
File imageFile = new File(picturesDirectory, timestamp + ".jpg");
return imageFile;
}
onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) // resultCode: -1
{
if(requestCode == CAMERA_REQUEST_CODE ) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if(requestCode == CAMERA_REQUEST_CODE1)
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Croppedimage(result, iv); // my problem !
/*
* Here i want to use if or switch statement to can use iv1
for second camera button! HOW?
*
* example
*
* if(for first camera button)
* {
* Croppedimage(result, iv);
* }
*
* if(for second camera button)
* {
* Croppedimage(result, iv1);
* }
*
* */
}
else if(resultCode ==
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
}
startCropImageActivity function
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
Croppedimage function
public void Croppedimage(CropImage.ActivityResult result,ImageView iv)
{
Uri resultUri = null; // get image uri
if (result != null) {
resultUri = result.getUri();
}
//set image to image view
iv.setImageURI(resultUri);
}
____________________________________________________________________________
The problem
The cropped image for second Button set in first Imageview.
Need to find way to reach to iv1 in onActivityResult for second camera Button.
Any suggestions?
Library use for crop image
THANKS.
Looking in the issues on the GitHub respository I found this one, that seems similar to yours, you can set a custom request code when starting the crop activity.
So you can start the activity with 2 different request codes and check which one has been used on onActivityResult
private static final RC_CROP = 100;
private static final RC_CROP1 = 200;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) // resultCode: -1
{
if (requestCode == CAMERA_REQUEST_CODE) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == CAMERA_REQUEST_CODE1) {
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP1);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == RC_CROP) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on first ImageView
}
if (requestCode == RC_CROP1) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on second ImageView
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
private void startCropImageActivity(Uri imageUri, int requestCode) {
Intent vCropIntent = CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.getIntent(this);
startActivityForResult(vCropIntent, requestCode)
}
I suggest also to use a switch statement when checking the requestCode

Image displays when choosing from gallery but not when capturing from camera

On the press of a button, dispatchTakePictureIntent() lets the user choose between taking a picture or choosing one from the gallery four times. These four URIs are stored in an ArrayList and the four should be shown in their respective ImageViews. The problem I'm having is that when I "capture a picture", it doesn't show in the ImageView right away; but the pictures I chose from gallery do.
The picture I captured is properly saved and can be found in "choose from gallery" the next time I press the button. Can anybody see what I'm doing wrong?
takePictureIntent():
private void dispatchTakePictureIntent() {
for(int i = 0; i < 4; i++) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
if(id.equals(HAPPY_ID))
startActivityForResult(chooserIntent, REQUEST_HAPPY_PHOTO);
if(id.equals(SURPRISED_ID))
startActivityForResult(chooserIntent, REQUEST_SURPRISED_PHOTO);
if(id.equals(AFRAID_ID))
startActivityForResult(chooserIntent, REQUEST_AFRAID_PHOTO);
if(id.equals(UPSET_ID))
startActivityForResult(chooserIntent, REQUEST_UPSET_PHOTO);
if(id.equals(SAD_ID))
startActivityForResult(chooserIntent, REQUEST_SAD_PHOTO);
}
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_HAPPY_PHOTO || requestCode == REQUEST_SURPRISED_PHOTO || requestCode == REQUEST_AFRAID_PHOTO ||
requestCode == REQUEST_UPSET_PHOTO || requestCode == REQUEST_SAD_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
//Log.d("doing ids", "right before id");
//Log.d("doing ids", "id is " + id);
if(requestCode == REQUEST_HAPPY_PHOTO) {
//Log.d("doing ids", "in happy");
happyList.add(selectedImageUri);
}
if(requestCode == REQUEST_SURPRISED_PHOTO) {
//Log.d("doing ids", "in surprised");
surprisedList.add(selectedImageUri);
}
if(requestCode == REQUEST_AFRAID_PHOTO) {
//Log.d("doing ids", "in surprised");
afraidList.add(selectedImageUri);
}
if(requestCode == REQUEST_UPSET_PHOTO) {
//Log.d("doing ids", "in surprised");
upsetList.add(selectedImageUri);
}
if(requestCode == REQUEST_SAD_PHOTO) {
//Log.d("doing ids", "in surprised");
sadList.add(selectedImageUri);
}
}
}
}
Try this, this works for me
public Uri captureImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (chooserIntent.resolveActivity(getPackageManager()) != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Image File name");
Uri takenImageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, takenImageUri);
startActivityForResult(intentPicture, MyConstants.REQUEST_IMAGE_CAPTURE);
return takenImageUri;
}
return null;
}
public String getRealPathFromURI(Uri contentUri){
try {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e){
return contentUri.getPath();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
switch (requestCode){
case MyConstants.REQUEST_IMAGE_CAPTURE:
if (takenImageUri != null) {
Uri imagePath =getRealPathFromURI(takenImageUri,this));
}
}
}
}
rather than looping for 4 times, why not make each imageView an OnClickListener to get the image one by one?

How to pass default image to previous activity if no image is selected

In my app, I have a camera function. User can capture image or pick from gallery.
Activity B
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
if(selectedImage!=null) {
returnIntent.putExtra("img_uri", selectedImage.toString());
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
When submit button is clicked, it will return to previous activity.
Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
imgURI = Uri.parse(data.getStringExtra("img_uri"));
if (mClickedPosition == -1) {
if (obj != null)
obj.addNewItem(imgURI);
} else {
if (obj != null)
obj.changeItem(mClickedPosition, imgURI);
}
}
}
}
My question now is how to pass a default image to Activity A If
user didn't select any image ?
This is the xml imageView in Activity B
<ImageView
android:paddingTop="30dp"
android:layout_gravity="center"
android:layout_width="330dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="#mipmap/no_image"
android:scaleType="fitXY"
android:id="#+id/imageView"
android:layout_weight="0.50" />
If no image selected, I want #mipmap/no_image return to Activity B. Is it possible ? Thanks.
You can pass an Uri of your image stored in resources by the next way:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
if(selectedImage!=null) {
returnIntent.putExtra("img_uri", selectedImage.toString());
} else {
returnIntent.putExtra("img_uri", Uri.parse("android.resource://your.package.name/mipmap/no_image").toString());
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Then you can use it as usual Uri to show the image in ImageView.
ByDefault set value of selectedImage to "default".
Now in your addNewItem() and changeItem() check value passed in imageUri
if(imageUri.equalsIgnoreCase("default"))
// set your default image that is #mipmap/no_image
else
// set image you are getting from imageUri
Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}else{
//set default
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}else{
//set default
}
default{
//set default
}
}
You don't need to return a default image to Activity A. Like others wrote, you just have to prepare for the condition when the user doesn't select any image.
Modify your onActivityResult for Activity A like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data!=null){
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
}
}
break;
default:
//Your default image goes here, when the user doesn't select either of the two options
imageView.setImageResource(R.drawable.<default_image>);
break;
}
}

Categories