CropActivity doesn't open after picking image - java

I tired to do same as in https://www.simplifiedcoding.net/crop-image-android-tutorial/. Pick image from gallary and after crop it. But when i'm included it to my fragment it's open gallary but after doesn't show crop activity. But when i did the same directly in activity its work!
My fragment onViewCreated
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SetupUI(view);
SetupProfile();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
FragmentAdapterProfile adapter = new FragmentAdapterProfile(getActivity(), getActivity().getSupportFragmentManager());
// Set the adapter onto the view pager
pager.setAdapter(adapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.profileTabs);
tabLayout.setupWithViewPager(pager);
tabLayout.getTabAt(0).setText("About");
tabLayout.getTabAt(1).setText("Setting");
tabLayout.getTabAt(2).setText("Post");
changeavatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onSelectImageClick(v);
}
});
}
The picking
public void onSelectImageClick(View view) {
CropImage.startPickImageActivity((Activity) context);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(context, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(context, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
avatar.setImageURI(result.getUri());
Toast.makeText(context, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(context, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(context, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.setAspectRatio(1,1)
.start((Activity) context);
}

So i sloved this problem do the next.
I just created secondary Activity (empty) and call crop function in activity after it's work. Problem was in Contexts and Actvities.

Related

picasso does not display photos from the gallery

I want to add a photo from the gallery using picasso to imageView, but it is not displayed, photos from the Internet are displayed and those that were photographed from the camera are not
enter code here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_PICK_GALLERY_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
image_uri = data.getData();
Picasso.with(this)
.load(image_uri)
.error(R.drawable.defaultimage)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
image.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
image.setImageDrawable(errorDrawable);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
} else {
//startActivity(new Intent(Main2Activity.this, MyActivity.class));
}
}
In High API level devices. you need to add this line in Manifest Application tag
android:requestLegacyExternalStorage="true"

How to pass image gotten from camera or gallery to another activity

1. User selects a button to either upload from gallery or capture from camera
From gallery
choose_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
// Sets the type as image/*. This ensures only components of type image are selected
intent.setType("image/*");
//We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
String[] mimeTypes = {"image/jpeg", "image/png"};
intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
// Launching the Intent
startActivityForResult(intent,1);
}
});
From camera
capture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(UploadActivity2.this, BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
startActivityForResult(intent, 0);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
2. User selects a photo from gallery or capture from camera and the image is displayed in the current activity
public void onActivityResult(int requestCode,int resultCode,Intent data){
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
//Display image with glide
Glide.with(this).asBitmap().load(imgDecodableString).into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<?
super Bitmap> transition) {
display_image.setImageBitmap(resource);
display_image.setVisibility(View.VISIBLE);
}
}
//If request is from camera
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 0:
//Display image in current activity
Glide.with(this)
.load(cameraFilePath)
.into(display_image);
/*display_image.setImageURI(Uri.parse(cameraFilePath));*/
display_image.setVisibility(View.VISIBLE);
break;
}
}
3. I have a 'NEXT' button and when clicked I want to transfer the image displayed (Gotten from either the Gallery or Camera) to another activity, I havn't written a code for passing the image yet
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
startActivity(intent);
}
});
4. I want to know the best way to do this without affecting image quality and memory because in the next activity (UploadAcitivity3), I will be uploading the image passed to the server and saving in a directory
Please follow the steps to achieve this:
Option - 1: If you want to pass multiple images then use below:
Step - 1: Store the selected images path in an ArrayList like below:
private ArrayList<String> selectedImages = new ArrayList<>();
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImages.add(imgDecodableString);
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImages.add(cameraFilePath);
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putStringArrayListExtra("SELECTED_IMAGES", selectedImages);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
ArrayList<String> selectedImages = getIntent().getStringArrayListExtra("SELECTED_IMAGES");
}
Option - 2: If you want to pass single image then use below:
Step - 1: Store the selected image path like below:
private String selectedImage;
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImage = imgDecodableString;
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImage = cameraFilePath;
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("SELECTED_IMAGE", selectedImage);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
String selectedImage = getIntent().getStringExtra("SELECTED_IMAGE");
Glide.with(this).load(selectedImage).into(image_view);
}
You can send the image path through Intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("path", imagePath);
startActivity(intent);
}
});
You already have image path for capturing image is cameraFilePath
and for gallery image imgDecodableString.
Declare String imagePath; as class variable and assign them in onActivityResult.
imagePath = imgDecodableString;//For Gallery
imagePath = cameraFilePath;//For Capture image
Receive path in UploadActivity3.class
String imagePath = getIntent().getStringExtra("path");
Use this path in second activity as you want.

how do I get my intent to work with Google Place Autocomplete?

Can you tell me what I need to do to make my intent work please? When the user clicks mEditInit, the Places drop down menu appears.
When the user clicks the place in the menu, I want to send this back to mEditInit
I've used intents before but not working in this case.
public class MyActivity extends AppCompatActivity {
String stuff;
private EditText mEditInit;
public static final int AUTOCOMPLETE_REQUEST_CODE = 1;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mEditInit = (EditText) findViewById(R.id.edit_message);
mEditInit.setX(0);
mEditInit.setY(250);
//Get the bundle
Bundle bundle = getIntent().getExtras();
if (stuff != null && !stuff.isEmpty())
//Extract the data…
{ stuff = bundle.getString("stuff");
mEditInit.setText(stuff);
}
Places.initialize(this, getString(R.string.places_api_key));
mEditInit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "bowwow", Toast.LENGTH_SHORT).show();
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields).build(MyActivity.this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
//setResult(RESULT_OK, intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
//Toast.makeText(MyActivity.this, place.getName(), Toast.LENGTH_SHORT).show();
Toast.makeText(MyActivity.this, place.getName(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, MyActivity.class);
String getrec= place.getName();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("stuff", getrec);
//Add the bundle to the intent
i.putExtras(bundle);
// Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
// Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
// super.onActivityResult(requestCode, resultCode, data);
}
}
}
In your onActivityResult method, you do not need any extra.
Just call the method setText() on your EditText:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
//Toast.makeText(MyActivity.this, place.getName(), Toast.LENGTH_SHORT).show();
mEditInit.setText(place.getName());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
// Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
// super.onActivityResult(requestCode, resultCode, data);
}
}

How to recognize landmarks using Firebase ML kit?

I'm creating an application for recognizing landmarks.
When the image is recognized, the result should fall to onSuccess, but instead comes to onFailure.
The following message is displayed in the Log:
If you have not set up billing, please go to the Firebase Console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan= true
If you are specifying a debug API Key override and turning on API Key restrictions, make sure the restrictions are set up correctly.
When I click on the link I see the following page:
https://login.corp.google.com/request?s=firebase.corp.google.com:443/uberproxy/&d=https://firebase.corp.google.com/u/0/project/_/overview%3FpurchaseBillingPlan%3Dtrue%26upxsrf%3DAKKYJRc2HD6ROcy9V9DxnYxw-pd8yGnml-oEi37m5hKhkWurWQ:1557057663745&maxAge=1200&authLevel=2000000&keyIds=X-q,k02
What will I need to to do?
public class RecognizeLandmarks extends AppCompatActivity {
EditText mResultEt;
ImageView mPreviewIv;
TextView tvLName, tvLiD, tvLConfidence, tvLlatitude, tvLlongitude;
public static final int CAMERA_REQUEST_CODE = 200;
public static final int STORAGE_REQUEST_CODE = 400;
public static final int IMAGE_PIC_GALLERY_CODE = 1000;
public static final int IMAGE_PIC_CAMERA_CODE = 1001;
private static final String TAG = "MyLog";
String cameraPermission[];
String storagePermission[];
Uri image_uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recognize_landmarks);
androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("Click image button to insert Image");
mResultEt = findViewById(R.id.resultEt);
mPreviewIv = findViewById(R.id.imageIv);
tvLName = findViewById(R.id.tvLName);
tvLiD = findViewById(R.id.tvLiD);
tvLConfidence = findViewById(R.id.tvLConfidence);
tvLlatitude = findViewById(R.id.tvLlatitude);
tvLlongitude = findViewById(R.id.tvLlongitude);
//camera permission
cameraPermission = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//storage permission
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflate menu
getMenuInflater().inflate(R.menu.menu_recognize_text, menu);
return true;
}
//handle actionbar item clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId( );
if (id == R.id.addImage) {
showImageImportDialog( );
}
if (id == R.id.settings) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show( );
}
return super.onOptionsItemSelected(item);
}
private void showImageImportDialog() {
// items to display in dialog
String[] items = {" Camera", " Gallery"};
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Select Image");
dialog.setItems(items, new DialogInterface.OnClickListener( ) {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//camera option clicked
/*for os Marshmallow and above we need to ask runtime permission for camera and storage*/
if (!checkCameraPermission()) {
//camera permission not allowed, request it
requestCameraPermission();
} else {
//permission allowed, take picture
pickCamera();
}
}
if (i == 1) {
//gallery option clicked
if (!checkStoragePermission()) {
//storage permission not allowed, request it
requestStoragePermission();
} else {
//permission allowed, take picture
pickGallery();
}
}
}
});
dialog.create().show();
}
private void pickGallery() {
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
//set intent type to image
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PIC_GALLERY_CODE);
}
private void pickCamera() {
//intent to take image from camera, it will also be save to storage to get high quality image
ContentValues values = new ContentValues( );
values.put(MediaStore.Images.Media.TITLE, "NewPic"); //title of the picture
values.put(MediaStore.Images.Media.DESCRIPTION, "Image to text"); //description
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PIC_CAMERA_CODE);
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_REQUEST_CODE);
}
private boolean checkCameraPermission() {
/*Check camera permission and return the result
* in order to get high quality image we have to save image to external storage first
* before inserting to image view that`s why storage permission will also be required */
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickCamera();
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
case STORAGE_REQUEST_CODE:
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickGallery( );
}
else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//got image from camera or gallery
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PIC_GALLERY_CODE) {
//got image from gallery now crop it
CropImage.activity(data.getData( ))
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
if (requestCode == IMAGE_PIC_CAMERA_CODE) {
//got image from camera crop it
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
}
//get cropped image
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result1 = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result1.getUri( ); // get image uri
//set image to image view
mPreviewIv.setImageURI(resultUri);// past image in iV
//get drawable bitmap for text recognition
BitmapDrawable bitmapDrawable = (BitmapDrawable) mPreviewIv.getDrawable( );
Bitmap bitmap = bitmapDrawable.getBitmap( );
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionCloudDetectorOptions options =
new FirebaseVisionCloudDetectorOptions.Builder( )
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(15)
.build( );
FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance( )
.getVisionCloudLandmarkDetector(options);
Task<List<FirebaseVisionCloudLandmark>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionCloudLandmark>>( ) {
#Override
public void onSuccess(List<FirebaseVisionCloudLandmark> firebaseVisionCloudLandmarks) {
// Task completed successfully
// ...
for(FirebaseVisionCloudLandmark landmark : firebaseVisionCloudLandmarks) {
//Rect bounds = landmark.getBoundingBox();
String landmarkName = landmark.getLandmark( );
tvLName.setText(landmarkName);
String entityId = landmark.getEntityId( );
tvLiD.setText(entityId);
float confidence = landmark.getConfidence( );
tvLConfidence.setText(Float.toString(confidence));
// Multiple locations are possible, e.g., the location of the depicted
// landmark and the location the picture was taken.
for(FirebaseVisionLatLng loc : landmark.getLocations( )) {
double latitude = loc.getLatitude( );
tvLlatitude.setText(Double.toString(latitude));
double longitude = loc.getLongitude( );
tvLlongitude.setText(Double.toString(longitude));
}
}
}
})
.addOnFailureListener(new OnFailureListener( ) {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
Log.d(TAG,e.getMessage());
Toast.makeText(RecognizeLandmarks.this, "Recognizing Failed", Toast.LENGTH_SHORT).show( );
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//if there is any error show it
Exception error = result1.getError( );
Toast.makeText(this, "" + error, Toast.LENGTH_SHORT).show( );
}
}
}
}
Result
D/MyLog: If you haven't set up billing, please go to Firebase console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan=true. If you are specifying a debug Api Key override and turned on Api Key restrictions, make sure the restrictions are set up correctly
ML Kit's landmark detection does not run on the device itself, but uses Google Cloud Vision. For this reason your project needs to be on a paid plan, before you can use landmark detection. The first 1000 calls are free, after which you will be charged for additional calls.

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

Categories