Prevent gallery screen to be show after taking picture from camera Android - android

I am facing a problem where in when I am trying to crop an image after it has picked from Gallery or Camera.
When I choose the image from gallery it gets cropped correctly without any problem. When I choose image from camera, the cropping is done properly but it shows me an "intermediate" screen as seen below without taking me directly to the crop screen.
Note: Picture above is just for representation purposes to show the "intermediate" Recent screen.
I don't want this "intermediate" Recent screen to be displayed. Instead I want to directly navigate to the crop intent. In apps like Whatsapp this behavior is not seen when someone changes his/her profile pic. It directly navigates to crop intent without showing "intermediate" screen.
Can someone help solve this problem?
Here is my complete code
/**
* This activity is used to display profile picture and update the same
*
*/
public class ChangeProfilePhotoActivity extends BaseActivity implements
View.OnClickListener {
private TextView mTvTitle;
private ImageView mBtnChangePhoto;
private ImageView mIvProfileImage;
public static final int CROP_PIC_REQUEST_CODE = 3;
public static final int TAKE_PICTURE = 1;
public static final int GALLERY_IMAGE = 2;
public static final int IMAGE_CHOOSER_INTENT = 4;
int PERMISSION_ALL = 10;
String[] PERMISSIONS = { Manifest.permission.CAMERA};
//private Uri mImageUri;
//private Uri mCropImageUri;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_photo);
initUI();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void initUI() {
mBtnChangePhoto = (ImageView) findViewById(R.id.btnChangePhoto);
mIvProfileImage = (ImageView) findViewById(R.id.profile_image);
mBtnChangePhoto.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnChangePhoto:
//launch intent chooser
getPickImageIntent(this);
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case IMAGE_CHOOSER_INTENT:
if(data!=null){
String action = data.getAction();
Uri selectedImageUri = data.getData();
//send image for cropping
doCrop(selectedImageUri);
}
break;
case CROP_PIC_REQUEST_CODE:
if(data!=null){
Bundle extras = data.getExtras();
if(extras != null) {
Bitmap bmp = (Bitmap) extras.get("data");
mIvProfileImage.setImageBitmap(bmp);
}
}
break;
default:
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void doCrop(Uri picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC_REQUEST_CODE);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
public void getPickImageIntent(Context context) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//startActivityForResult(pickIntent, GALLERY_IMAGE);
Intent takePhotoIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
/* String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/crop_image.jpg";
File imageFile = new File(imageFilePath);
Uri picUri = Uri.fromFile(imageFile); // convert path to Uri
takePhotoIntent.putExtra( MediaStore.EXTRA_OUTPUT, picUri );*/
//takePhotoIntent.putExtra("return-data", false);
//startActivityForResult(takePhotoIntent, TAKE_PICTURE);
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
context.getString(R.string.pick_image_intent_text));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[intentList.size()]));
}
startActivityForResult(chooserIntent, IMAGE_CHOOSER_INTENT);
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
try {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
}

You're launching an intent. That means you're handing control off to another app. After that, you have no control over what happens. Of course what happens will be different on every device, as some OEMs will use their own Gallery app or Camera app that may behave completely differently.
So no, there's no way to prevent them from doing that extra screen. If you want total control, take the picture yourself via the camera or camera2 apis instead of calling an Intent. (Note: I don't actually suggest this, but if you want control its the only way).

Related

Capture a custom image size with the camera or crop it

Am working on OCR system which is requiring to capture image and do OCR, i would like to capture part of the paper (Exact where intended text is) or crop captured image before passing it to OCR processing for better results.
I tried bellow code but i can't make it to what am trying to archive as am beginner to android java
private void startCameraActivity() {
try {
String IMGS_PATH = Environment.getExternalStorageDirectory().toString() + "/ocr/imgs";
prepareDirectory(IMGS_PATH);
String img_path = IMGS_PATH + "/ocr.jpg";
outputFileUri = Uri.fromFile(new File(img_path));
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
takePictureIntent.putExtra("crop", "true");
takePictureIntent.putExtra("scale", true);
takePictureIntent.putExtra("aspectX", 1);
takePictureIntent.putExtra("aspectY", 1);
takePictureIntent.putExtra("outputX", 150);
takePictureIntent.putExtra("outputY", 100);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, PHOTO_REQUEST_CODE);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
//making photo
if (requestCode == PHOTO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
doOCR();
} else {
Toast.makeText(this, "ERROR: Image was not obtained.", Toast.LENGTH_SHORT).show();
}
}
private void doOCR() {
prepareTesseract();
startOCR(outputFileUri);
}
Am someone help me out here, Thanks.
NOTE
takePictureIntent.putExtra("crop", "true");
takePictureIntent.putExtra("scale", true);
takePictureIntent.putExtra("aspectX", 1);
takePictureIntent.putExtra("aspectY", 1);
takePictureIntent.putExtra("outputX", 150);
takePictureIntent.putExtra("outputY", 100);
After clearning my cache i noted the above code is opening complete action with apps which can crop image and everything is fine now.
Thanks.

Cannot Upload Image From Gallery in Android Studio

I want to upload image from gallery in my android app. When I click on button, the gallery should be opened. After selecting image, I want to open another activity named UploadActivity. There the thumbnail of the image should be previewed. The Upload Button will below the thumbnail.
But when I Choose photo from gallery, then the thumbnail of the image are not previewing. I am unable to upload the photo also. My Code goes here: (Scan.Java)
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int SELECT_IMAGE = 2;
private Uri fileUri; // file url to store image/video
ImageView dummy;
private Button btnCapturePicture;
private Button btnGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan);
dummy = (ImageView) findViewById(R.id.dummyphoto);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnGallery = (Button) findViewById(R.id.btnGallery);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
btnGallery.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openGallery();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
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);
}
/**
* Launching Gallery to Choose Image
*/
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* 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
// launching upload activity
launchUploadActivity(true);
} 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 == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(Scan.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
UploadActivity.Java Code goes here:
private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
btnUpload = (Button) findViewById(R.id.btnUpload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
// Receiving the data from previous activity
Intent i = getIntent();
// image path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
/**
* Displaying captured image on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
Here is Logcat:
E/MainActivity: Response from server: java.io.FileNotFoundException: /mnt/sdcard/Pictures/master/IMG_20170127_152930.jpg: open failed: ENOENT (No such file or directory)
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "IMG_20170127_152930.jpg");
//Try this.
After these changes i suggested below I hope your problem will be solved:
Remove these two lines from openGallery() because I think they are redundant.
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
They are needed when we use Intent.ACTION_PICK. So after editing openGallery() looks like:
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
Add this statement in your onActivityResult() :
fileUri = data.getData();
so it looks:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
else if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
fileUri = data.getData(); //added this line
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Same applies to the camera intent also.
Request EXTERNAL_STORAGE permission and also run time permission if your target Android version is 6.0 or above.
EDIT:
Sorry couple of things I have not mentioned those are required are given bellow:
You may like to send the Uri instead of path this way:
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(this, UploadActivity.class);
i.setData(fileUri);
// i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
And then in UploadActivity do the following:
...
private InputStream mInputStream; // Use this stream to create bitmap and upload to server
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Receiving the data from previous activity
Intent i = getIntent();
try {
mInputStream = getContentResolver().openInputStream(i.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
...
}
...
...
private void previewMedia(boolean isImage){
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(mInputStream,null,options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
...
This works for me and hope will work on you too.

Capture and Crop Image and save croped Image

I am trying to capture an image and save cropped image instead of original image with specified name.
At the moment I am able to crop and show on imageview but I need to know how to save cropped image instead of original, Here is the code.
final int CAMERA_CAPTURE = 1;
final int CROP_PIC = 2;
private Uri picUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn = (Button) findViewById(R.id.capture_btn);
captureBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData();
performCrop();
}
// user is returning from cropping the image
else if (requestCode == CROP_PIC) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
/**
* this function does the crop operation.
*/
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 2);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
I am new to android and I really want to know how I can do this, any kind of help is much appriciated.
So the question is: How to save a bitmap
Sometimes saving bitmaps takes a long time. I suggest you to use AsyncTask in order to avoid annoying lags in your app.
public class saveFile extends AsyncTask<Void, Void, File>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);//Show user that app is working in backgrind
}
#Override
protected File doInBackground(Void... params) {
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/CropedImage";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
String format = new SimpleDateFormat("yyyyMMddHHmmss",
java.util.Locale.getDefault()).format(new Date());
File file = new File(dir, format + ".png");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(file);
thePic.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
return file;
}
#Override
protected void onPostExecute(File result) {
progressBar.setVisibility(View.INVISIBLE);
String respath=result.getPath().toString();
Toast.makeText(MainActivity.this, "Saved at "+respath, Toast.LENGTH_LONG).show();
MediaScannerConnection.scanFile(MainActivity.this, new String[] { result.getPath() }, new String[] { "image/jpeg" }, null);
}
}
And then call AsyncTask:
new saveFile().execute();
Android does not have any crop intent you can download crop libraries Click here

Activity associated with image cropping libraries does not destroy

I have tried to solve this problem from many different links but does not worked for me.I am using Android Image Cropper library for cropping images. Whenever i click on the button "upload image" it start the cropping activity and when i am done the cropped image is set in an imageview in "upload image" activity and after clicking "Proceed" button login is successful and i am directed to login activity but when i back press the login activity the "Upload image" activity is still there and is not destroyed. I have another activity called Update Activity that uses this Cropping activity and that activity also behaves in the same manner. So i want the "Upload image" to destroy. Thanks in advance
package com.donateblood.blooddonation;
public class CroppingActivity extends AppCompatActivity {
private CropImageView mCropImageView;
public static Bitmap finalImage = null;
public static Bitmap newImage = null;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onSetImageClick(View view) {
if(UpdateActivity.UpdatingPhoto){
newImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else {
finalImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UploadImage.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onBackPressed() {
UpdateActivity.UpdatingPhoto = false;
super.onBackPressed();
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (Foolish android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof ErrnoException) {
return true;
}
} catch (Exception e) {
}
return false;
}
}
package com.donateblood.blooddonation;
public double longitude;
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
code = (EditText) findViewById(R.id.code);
ButterKnife.inject(this);
myimage = CroppingActivity.finalImage;
CheckImage();
// Upload image ====================================
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(code.length()==0){
Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
}
else {
Prcoess();
}
}
});
}
public void CheckImage(){
if(myimage!=null){
// set the image
// myimage = getRoundedShape(myimage);
Uri uri = getImageUri(myimage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Picasso.with(UploadImage.this).load(file).resize(200,200).placeholder(R.drawable.user).error(R.drawable.error)
.transform(new CircleTransform()).centerCrop()
.into(ImageUpload);
}else {
encodedPhotoString= null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UploadImage.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
// Processing and adding user to database from here ====================================
public void Prcoess(){
String userentered=code.getText().toString();
String sentcode = SignupActivity.Code;
// resize the image to store to database
//myimage= getResizedBitmap(myimage,200,200);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
if(userentered.equals(sentcode) && encodedPhotoString!=null ){
new AddUserAsync().execute();
}
else {
Toast.makeText(getBaseContext(), "Wrong code or No image uploaded", Toast.LENGTH_LONG).show();
}
}
public class AddUserAsync extends AsyncTask<Void,Void,Void> {
JSONObject json =null;
boolean added = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
GenerateGCMID();
email= email.trim().toLowerCase();
HashMap<String ,String> userDetails = new HashMap<>();
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
userDetails.put("ID",ID);
userDetails.put("Name",name);
userDetails.put("email",email);
userDetails.put("password",password);
userDetails.put("age",age);
userDetails.put("number",number);
userDetails.put("bloodgroup",bloodgroup);
userDetails.put("lat",latitude+"");
userDetails.put("longi",longitude+"");
userDetails.put("image",encodedPhotoString);
json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/Adduser.php",userDetails);
if(json!=null){
added = true;
}else {
added = false;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if(added==true){
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}else {
Toast.makeText(getBaseContext(), "Error creating account. Try again", Toast.LENGTH_LONG).show();
}
}
}
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
// Go to another activity on success ====================================
public void onSignupSuccess() {
// stop the service we got the latitude and longitude now
stopService(new Intent(this, GPSTracker.class));
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
check this method you are not finishing the UploadActivity here:-
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UploadActivity.this.finish();
}
});

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

Categories

Resources