Camera and gallery crop options - android

I am using camera option in my app but it works some devices only. Also I need crop options.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {
mImageCaptureUri = data.getData();
System.out.println("Gallery Image URI : "+mImageCaptureUri);
CropingIMG();
}
}

To fix camera issue, I have used following methods
CameraIntentHelper
onSaveInstanceState
onRestoreInstanceState
onActivityResult
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoSuiteActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
if (mCameraIntentHelper != null) {
mCameraIntentHelper.startCameraIntent();
} else {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.png";
File imageFile = new File(imageFilePath);
picUri = Uri.fromFile(imageFile); // convert path to Uri
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(takePictureIntent, CAMERA_CAPTURE);
}
} else if (options[item].equals("Choose from Gallery")) {
Toast.makeText(PhotoSuiteActivity.this, "Not yet Ready...!", Toast.LENGTH_SHORT).show();
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
mImageCaptureUri = photoUri;
Bitmap photo = BitmapHelper.readBitmap(PhotoSuiteActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
imageView.setImageBitmap(photo);
CropingIMG();
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, PhotoSuiteActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}

Related

How to set multiple image in multiple imageview

I am new to programming and android. I'm building an app that allows users to upload multiple images,I am using two image view, pic from camera to set one image view and another image view to set another camera pic from to set another images and same thing pic from gallery.I need to upload 2 different image in to different image view. How can I upload? i attached the my code kindly solve my issue.
public class MainActivity extends AppCompatActivity {
ImageView imageView1, imageView2;
private Button btn;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.image1);
imageView2 = findViewById(R.id.image2);
requestMultiplePermissions();
btn = findViewById(R.id.btn);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
switch (requestCode) {
case R.id.image1:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView1.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.image2:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView2.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<com.karumi.dexter.listener.PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
}
public class MainActivity extends AppCompatActivity {
ImageView imageView1, imageView2;
private Button btn;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
**private int clickImage;**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.image1);
imageView2 = findViewById(R.id.image2);
requestMultiplePermissions();
btn = findViewById(R.id.btn);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**clickImage=1;**
showPictureDialog();
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**clickImage=2;**
showPictureDialog();
}
});
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
switch (**clickImage**) {
case 1:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView1.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
case 2:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView2.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<com.karumi.dexter.listener.PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
}

Selected from gallery or camera photos not displaying in the ImageView

Camera taken photo or selected photo is not displaying in ImageView. I'm using the following code:
private void attachFile() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(mContext);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Photo"), SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA && data != null) {
Log.d(TAG, "onActivityResult: done take photo");
Uri mImageCaptureUri = data.getData();
imageView.setImageURI(mImageCaptureUri);
/*Bundle bundle = data.getExtras();
final Bitmap bitmap = (Bitmap) bundle.get("data");
mOnphotoSelectedListener.getImageBitmap(bitmap);*/
} else if (requestCode == SELECT_FILE) {
Uri selectImageUri = data.getData();
mOnphotoSelectedListener.getImagePath(selectImageUri);
//imageView.setImageURI(selectImageUri);
//Picasso.with(mContext).load(selectImageUri).into(imageView);
//Picasso.with(this).load(selectImageUri).into(imageView);
}
}
}
i have this code i hope it will work for you its correct working
i set onclick for ImageProfile and i give to user picture + crop
i hope it will work for u
private void mImage_profileOnclick() {
int persmissonCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
if (persmissonCheck == PackageManager.PERMISSION_DENIED) {
Req();
}else {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_open_device);
Button pic, gal;
pic = (Button) dialog.findViewById(R.id.pick);
gal = (Button) dialog.findViewById(R.id.gallery);
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
dialog.cancel();
dialog.dismiss();
}
});
gal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialog.findViewById(R.id.cropImageView);
Button button = (Button) dialog.findViewById(R.id.bac);
cropImageView.setImageBitmap(imageBitmap);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mImage_profile.setImageBitmap(cropImageView.getCroppedImage());
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Dialog dialogs = new Dialog(getActivity());
dialogs.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialogs.findViewById(R.id.cropImageView);
cropImageView.setImageUriAsync(selectedImage);
Button button = (Button) dialogs.findViewById(R.id.bac);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap cropped = cropImageView.getCroppedImage();
mImage_profile.setImageBitmap(cropped);
dialogs.cancel();
dialogs.dismiss();
}
});
//dialogs.create();
dialogs.show();
}
break;
}
}
//#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void Req() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "شما مجوز استفاده از دوربین یا هر چیز دیگر را به برنامه نداده اید", Toast.LENGTH_SHORT).show();
}
else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
mImage_profileOnclick();
} }
Used below code inside the onActivityResult
if (requestCode == Activity.RESULT_OK) {
File user_dp;
if (requestCode == REQUEST_CAMERA && data != null) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
user_dp = destination;
//update_profilepic is ImageView reference
Picasso.with(getContext()).load(user_dp).into(update_profilepic);
} else if (requestCode == SELECT_FILE) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
//ivImage is image reference
ivImage.setImageBitmap(bm);
}
}
}
Instead of resultCode I have requestCode on the first line inside the if statement.

How to open camara and gallery in recyclerview onclick listener?

ItemAdapter.java
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textView;
String item;
private final Context context;
public ViewHolder(final View itemView) {
super(itemView);
context = itemView.getContext();
itemView.setOnClickListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==textView.getId()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
context.startActivity(intent);
}
else
{
Toast.makeText(context,"Hellooo",Toast.LENGTH_LONG).show();
}
}
});
textView = (TextView) itemView.findViewById(R.id.textView);
}
Try this
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
activeTakePhoto();
} else if (items[item].equals("Choose from Library")) {
activeGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void activeTakePhoto() { //open camera
String filename = "Pic_" + System.currentTimeMillis() + ".jpg";
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), filename);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
private void activeGallery() { // open gallery
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#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) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
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();
}
}
}
}

image view:second image is replaced by the first image captured

hello i am struck in this coding first of all i am having two image view's when we click one of them the chooser dialog box will open which is having two option 1.take photo 2.select from gallery when i select from galley everything is working fine where as the problem is,
when we select take photo option and after we had captured the image when setting its preview for the first image its working fine where as the problem here is in the second image. when we select take photo option and after capturing the photo it is replacing the image of the first image with the second image.
This is Java Code:
public class PrescriptionUpload extends ActionBarActivity {
ImageView uploadimage1, uploadimage2;
Bitmap imagemap, imagemapsec;
int imageupload = 1;
int imagesecpload = 2;
int requestcamera = 0;
Button uploadpric;
StringBuilder sb;
String uploadimg2;
Toolbar include2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prescriptionimages);
include2= (Toolbar) findViewById(R.id.include2);
setSupportActionBar(include2);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
uploadimage1 = (ImageView) findViewById(R.id.uploadimage1);
uploadimage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imageupload);
}
});
uploadimage2 = (ImageView) findViewById(R.id.uploadimage2);
uploadimage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectimage(imagesecpload);
}
});
}
private void selectimage(final int number) {
final CharSequence[] items = {"Take Photo", "Choose from Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(PrescriptionUpload.this);
builder.setTitle("Add Prescription");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, requestcamera);
} else if (items[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
number);
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == imageupload) {
try {
imagemap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage1.setImageBitmap(imagemap);
uploadimage2.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == imagesecpload) {
try {
imagemapsec = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
uploadimage2.setImageBitmap(imagemapsec);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == requestcamera) {
if (uploadimage1.getId()==R.id.uploadimage1){
Bitmap testurl = (Bitmap) data.getExtras().get("data");
uploadimage1.setImageBitmap(testurl);
uploadimage2.setVisibility(View.VISIBLE);
}else if (uploadimage2.getId()==R.id.uploadimage2){
Bitmap testurltwo = (Bitmap) data.getExtras().get("data");
uploadimage2.setImageBitmap(testurltwo);
}
}
}
}
i had solved my problem using onActivityResult and with the increment of the variable

how to capture image from camera, in fragment,

I am new to Android, and I have done lots of training but the image does not load from the camera. Below is my code for capturing image from camera or gallery:
public void showDiloag(){
Dialog dialog = new Dialog(getActivity());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Gallery", "Camera" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent
.createChooser(
intent,
"Choose a Picture");
getAcitivity.startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
break;
case 1:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
cameraIntent,
ACTION_REQUEST_CAMERA);
break;
default:
break;
}
}
});
builder.show();
dialog.dismiss();
}
And for display that photo:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == Utils.ACTION_REQUEST_GALLERY) {
// System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
String tempPath = JuiceAppUtility.getPath(
selectedImageUri, getActivity());
Bitmap bm = JuiceAppUtility
.decodeFileFromPath(tempPath);
imgJuice.setImageBitmap(bm);
} else if (requestCode == Utils.ACTION_REQUEST_CAMERA) {
Bitmap photo = (Bitmap) data.getExtras()
.get("data");
imgJuice.setImageBitmap(photo);
}
}
}
Also image is captured from camera and choose from gallery but it will not load in ImageView. Can anybody help me please?
Ya i found your problem
just remove below line and
getAcitivity.startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
and write down below code
startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
just remove getActivity
FRAGMENT SIDE
btnimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
private void showPictureDialog(){android.app.AlertDialog.Builder pictureDialog = new android.app.AlertDialog.Builder(getActivity());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// choosePhotoFromGallary();
choosePhotoFromGallary();
break;
case 1:
// takePhotoFromCamera();
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void takePhotoFromCamera() {
Uri resultUri;
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
resultUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, resultUri);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent, 22);
}
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 11);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK)
{
if (requestCode == 11) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
// String path = saveImage(bitmap);
// Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
iv_froncnic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
{
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
}
}
}
In parent ACTIVITY
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode==this.RESULT_OK){
super.onActivityResult(requestCode, resultCode, data);
setResult(RESULT_OK, data);
}
}

Categories

Resources