Do you know how to handle two onActivityResult()s in one activity?
I need to use my camera and search for my photos in one activity.
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CAPTURE = 1;
Button button_Vyber_Fotku, button_Fotak;
ImageView imageView_VyberFotku, imageView_Fotak;
private static final int PICK_IMAGE = 100;
Uri imageUri_vybrana;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_VyberFotku = (ImageView) findViewById(R.id.imageView_VyberFotku);
button_Vyber_Fotku = (Button) findViewById(R.id.button_Vyber_Fotku);
imageView_Fotak = (ImageView) findViewById(R.id.imageView_Fotak);
button_Fotak = (Button) findViewById(R.id.button_fotak);
if (!hasCamera())
{
button_Fotak.setEnabled(false);
}
}
public void Vyber_fotku_clicked(View v)
{
openGallery();
}
private void openGallery()
{
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri_vybrana = data.getData();
imageView_VyberFotku.setImageURI(imageUri_vybrana);
}
}
public boolean hasCamera()
{
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
public void PouzijFotakClicked(View v)
{
Intent vyfot = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(vyfot , REQUEST_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode1, int resultCode1, Intent data1)
{ if (requestCode1 == REQUEST_CAPTURE && resultCode1 == RESULT_OK)
{
Bundle extras = data1.getExtras();
Bitmap photo = (Bitmap) extras.get("data1");
imageView_Fotak.setImageBitmap(photo);
}
}
}
Instead of two different method for onActivityResults use single method and distinguish them according to their request code.
#Override
protected void onActivityResult(int requestCode1, int resultCode1, Intent data1){
if (requestCode1 == REQUEST_CAPTURE && resultCode1 == RESULT_OK){
Bundle extras = data1.getExtras();
Bitmap photo = (Bitmap) extras.get("data1");
imageView_Fotak.setImageBitmap(photo);
}
else if (resultCode1 == RESULT_OK && requestCode1 == PICK_IMAGE){
imageUri_vybrana = data1.getData();
imageView_VyberFotku.setImageURI(imageUri_vybrana);
}
}
Note: You can't have two declaration for single override method.
// define two variable camera and pick_image of int type pass value of request code of desired out put in activity onResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
//first one to pick image
//do somthing
}else if(resultCode == RESULT_OK && requestCode == Camera){
//use to take image from camera response
}
}
Check this
It works for me
private static final int CAMERA_ = 999;
private static final int GALLERY_ = 888;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_) {
if (resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
UtilsClass.mBitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView.setImageBitmap(UtilsClass.mBitmap);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}else if (requestCode == GALLERY_) {
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
UtilsClass.mBitmap = (BitmapFactory.decodeFile(picturePath));
imageView.setImageBitmap(UtilsClass.mBitmap);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
Related
I want to upload multiple images through android application to firebase. I want to get the URL of the image which i got in my second activity(ie, B Activity) to my first activityIA activity). I have tried many answers posted but I could not solve the issue. Can anyone help me please. Here is my code
B Activity
mSelectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
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 Picture"), RESULT_LOAD_IMAGE);
} });
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
totalItemsSelected = data.getClipData().getItemCount();
for(int i = 0; i < totalItemsSelected; i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
final int finalI = i;
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(finalI);
fileDoneList.add(finalI, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL=imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent()
idata.putExtra("imageURL", imageURL);
idata.putExtra("count",totalItemsSelected);
setResult(RESULT_OK, idata);
finish();
}
});
}
A activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
if (requestCode == 123) {
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
this.orderItem.setImageURL(imageURL);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
break;
case 2://added24
if(requestCode==100){//added24
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
newString=data.getStringExtra("count");
}
}
break;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.order_item_update, menu);
FrameLayout image_viewCount = (FrameLayout) menu.findItem(R.id.star).getActionView();
TextView image_count = (TextView) image_viewCount.findViewById(R.id.cart_badge);
image_count.setText(newString);
image_viewCount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),MultipleActivity.class);
Order.getInstance().getOrderItems();
startActivityForResult(intent,100);
}
});
I want to set the count (ie, "total selected" in image_count) but I am not able to get the value as I am not getting the value from Bactivity to A activity
change the onActivityResult in your A activity to,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123:
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
this.orderItem.setImageURL(imageURL);
} else if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
break;
case 100:
if (resultCode == RESULT_OK) {
imageURL = data.getStringExtra("imageURL");
newString = data.getStringExtra("count");
} else {
//Write your code if there's no result
}
break;
}
}
You were switching resultCode and the cases you used were 1 and 2. The int constant for RESULT_OK is -1.
And in your MultipleActivity activity, the condition data.getClipData() != null will only be true when there are multiple Uris to send back. When there is just one you can get it with getData. You can do it like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
final int finalI = i;
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(finalI);
fileDoneList.add(finalI, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL = imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent();
idata.putExtra("imageURL", imageURL);
idata.putExtra("count", totalItemsSelected);
setResult(RESULT_OK, idata);
finish();
}
});
}
} else {
Uri fileUri = data.getData();
String fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
StorageReference fileToUpload = mStorage.child("Images").child(fileName);
fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileDoneList.remove(0);
fileDoneList.add(0, "done");
uploadListAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
ImageUploadInfo imageUploadInfo = new ImageUploadInfo(taskSnapshot.getDownloadUrl().toString());
imageURL = imageUploadInfo.getImageURL();
imagesList.add(imageURL);
Intent idata = new Intent();
idata.putExtra("imageURL", imageURL);
idata.putExtra("count", 1);
setResult(RESULT_OK, idata);
finish();
}
});
}
}
}
Your issue is that the fileToUpload is async and you are creating them in a loop; you close the current activity when one of those tasks ends (the first one). You can simulate a semaphore, to mark the completion of each fileToUpload tasks and store the result in it, and in the onSuccess method, just check if all task instances are completed before closing the current activity and passing the result (which should be an array of objects btw).
As I understood:
Activity-A opens Activity-B using startActivityForResult.
and you want image url which you got in Activity-B to Activity-A via onActivityResult().
If so then,
you have to add your activity finish code in some action not into onActivityResult() of Activity-B.
Because adding it to onActivityResult() means you are waiting for the response of any Activity you open from Activity-B using startActivityForResult.
This question already has answers here:
Multiple onActivityResult for 1 Activity
(3 answers)
Closed 5 years ago.
I have an app where I want to use two buttons, one for opening the camera and the other should open the gallery and select a image.
What is the correct way to create the onActivityResult? I started with the camera and it works. I then added the select from gallery button with intent but the first "if"-clause is always triggered becauce REQUEST_TAKE_PHOTO is always true/1. In all the examples I could find they always used final static ints for these kind of tasks.
Should I not use final static ints and set them to the correct state before triggering the onActivityState?
How do people usually solve this?
static final int REQUEST_TAKE_PHOTO = 1;
static final int PICK_IMAGE_REQUEST = 1;
...
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Välj Bild"), PICK_IMAGE_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == REQUEST_TAKE_PHOTO) {
try {
setPic();
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == PICK_IMAGE_REQUEST && data.getData() != null) {
Uri uri = data.getData();
mImageView.setImageURI(uri);
}
} else {
Log.d("Error", "Error");
}
}
Why are using same request code fro both request . Change these.
static final int REQUEST_TAKE_PHOTO = 1;
static final int PICK_IMAGE_REQUEST = 1;
request code should be unique to one another so use like .
static final int REQUEST_TAKE_PHOTO = 1;
static final int PICK_IMAGE_REQUEST = 2;
onActivityresult() canbe like below .
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO) {
if (resultCode == RESULT_OK) {
// camera picture
} else {
// request canceled
}
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
mImageView.setImageURI(uri);
}
}
}
you can use switch statement in your OnActivityResult like this:
And you need to change your int values too Like this:
static final int REQUEST_TAKE_PHOTO = 1;
static final int PICK_IMAGE_REQUEST = 2;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case REQUEST_TAKE_PHOTO :
/// your code for this
break;
case PICK_IMAGE_REQUEST :
// your code here for image request.
break;
}
}catch (Exception e) {
}
I use Picasso to get an image from the gallery and set it to an ImageView, but it does not do it. Couldn't find a problem. What is the reason? And the interesting thing is that there was no error. I tested the program through my own device.
public class MainActivity extends AppCompatActivity {
String imageUri ;
ImageView img ;
private static final int GALLERY_REQUEST = 9391;
Button b ;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
imageUri = data.getData().toString() ;
loadImage() ;
}
else
{
super.onActivityResult(requestCode, resultCode, data);
}
}
private void loadImage() {
Picasso.with(this).load(imageUri).fit().centerInside().into(img);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.image);
b = (Button)findViewById(R.id.button) ; // it is button used to open //a gallery
}
//thins function called when button pressed
public void openGallery(View view) {
Intent i = new Intent(ACTION_PICK,EXTERNAL_CONTENT_URI) ;
startActivityForResult(i,GALLERY_REQUEST);
}
}
You called super.onActivityResult(requestCode, resultCode, data); which is wrong .
Do this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
Uri selectedImageURI = data.getData();
Picasso.with(this).load(selectedImageURI).fit().centerInside().into(img);
}
else
{
// handle this case
}
}
Problem Solved.
I forgot to add permission used to read external storage.
I am trying to get image from phone gallery or capturing image from camera..I have used 'me.villani.lorenzo.android:android-cropimage:1.1.+' for croping the image..It works well for getting image from phone gallery..While Capturing the image from camera,It captured the image but it cannot able to crop..It works fine on Choose from Image from gallery..Here i included my code,please have a look,
public class Details extends AppCompatActivity {
ImageView i1,i2;
Bitmap bitmapPic;
private static int REQUEST_PICTURE = 1;
private final static int REQUEST_PERMISSION_REQ_CODE = 34;
private static int REQUEST_CAMERA = 0, SELECT_FILE = 1, REQUEST_CROP_PICTURE = 2;
private static int CROP_IMAGE_SIZE = 200;
private static int CROP_IMAGE_HIGHLIGHT_COLOR = 0x6aa746F4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
android.support.v7.app.ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.hide();
}
i1 = (ImageView)findViewById(R.id.prof1);
i2 = (ImageView)findViewById(R.id.prof2);
i1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageOption();
}
});
}
private void selectImageOption() {
final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Details.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Capture Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent, SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
File croppedImageFile = new File(getFilesDir(), "Pic.jpg");
Uri croppedImage = Uri.fromFile(croppedImageFile);
if (requestCode == REQUEST_CROP_PICTURE && resultCode == RESULT_OK) {
bitmapPic = BitmapFactory.decodeFile(croppedImageFile.getAbsolutePath());
if (bitmapPic != null) {
i1.setImageBitmap(bitmapPic);
} else {
Toast.makeText(Details.this, "Image Error while Cropping", Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_OK && (requestCode == REQUEST_CAMERA || requestCode == SELECT_FILE)) {
showImageCropView(data, croppedImage);
}
}
private void showImageCropView(Intent data, Uri croppedImage) {
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(CROP_IMAGE_SIZE, CROP_IMAGE_SIZE, croppedImage);
cropImage.setOutlineColor(CROP_IMAGE_HIGHLIGHT_COLOR);
cropImage.setSourceImage(data.getData());
cropImage.setCircleCrop(true);
startActivityForResult(cropImage.getIntent(this), REQUEST_CROP_PICTURE);
}
}
Captured Image from Camera does not able to crop!Please give me better Solution for this.!Thanks in Advance
Bro, check this out. May solve your problem, you can crop the image from camera / gallery. link
set
<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat"/> <!-- optional (needed if default theme has no action bar) -->
to your manifest
call startCropImageActivity(null); in onclick method
this is the method :
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.setRequestedSize(320, 320, CropImageView.RequestSizeOptions.RESIZE_INSIDE)
.setMinCropWindowSize(0,0)
.setAspectRatio(1,1)
.setCropShape(CropImageView.CropShape.OVAL)
.start(this);
}
and in onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
((CircleImageView) findViewById(R.id.profileImage)).setImageURI(result.getUri());
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
Here I'm using CircleImageView as circle image
I am trying to crop the image as we are doing in facebook. I have used this link in my app: https://github.com/oginotihiro/cropview This is working fine for me.But here when I click on a button, its directly going to gallery and cropping the selected image.Instead of that I want to open camera in my device and click the image and I want to do cropping.How can I do this?Can someone help me.
I have tried this code.But I am not able to implement.
imageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reset();
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_PICK);
}
});
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog dialog = ProgressDialog.show(StudentDetails.this, null, "Please wait…", true, false);
cropView.setVisibility(View.GONE);
layout4.setVisibility(View.GONE);
resultIv.setVisibility(View.VISIBLE);
layout3.setVisibility(View.GONE);
layoutUpload.setVisibility(View.VISIBLE);
// editTextName.setVisibility(View.GONE);
buttonUpload.setVisibility(View.VISIBLE);
new Thread() {
public void run() {
croppedBitmap = cropView.getOutput();
runOnUiThread(new Runnable() {
#Override
public void run() {
// cropped image set
resultIv.setImageBitmap(croppedBitmap);
}
});
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
CropUtil.saveOutput(StudentDetails.this, destination, croppedBitmap, 1);
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
}.start();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_PICK) {
filePath = data.getData();
cropView.setVisibility(View.VISIBLE);
layoutImage.setVisibility(View.VISIBLE);
layout3.setVisibility(View.GONE);
layout4.setVisibility(View.VISIBLE);
textNameVal.setVisibility(View.GONE);
text1.setVisibility(View.GONE);
buttonUpload.setVisibility(View.GONE);
int x=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
int y=(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
cropView.of(filePath).withAspect(x,y).initialize(StudentDetails.this);
}
}
Step1: Start to open gallery
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
Step2: Get Image from gallery:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
With your case, you can crop at the onActivityResult method.
It will help you.
With camera:
Step1: Open camera
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
Step2: Get image from camera.
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
Step3: Add permission
<!-- Accessing camera hardware -->
<uses-feature android:name="android.hardware.camera" />