Hi I want to capture image and do some opration for that image in my next activity.I have tried to run the below code in Samsung and Moto G and its working fine.When I tried same code with redmi note3,after Clicking right mark it is coming to the same activity.How to solve this? This is my code:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(originalFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No camera app found!", Toast.LENGTH_LONG).show();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Bitmap imageData = null;
if (resultCode ==Activity.RESULT_OK) {
try
{
BitmapFactory.Options bitopt=new BitmapFactory.Options();
imageData = BitmapFactory.decodeFile(imagePath, bitopt);
Uri tempUri = getImageUri(getApplicationContext(), imageData);
Intent i = new Intent(this, Image_R.class);
i.putExtra("imageUri", tempUri.toString());
startActivityForResult(i, 3);
}
catch (Exception e) {
Toast.makeText(this, "Unable to save image", Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
}
}
replace this:--
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
Add this code to your activity tag inside your Manifest file.
android:configChanges="orientation|keyboardHidden|screenSize"
It will not let your current activity to destroy and re-create so you will get the result.
And if this doesn't work make sure that your Device is not on power/battery saving mode.
RedMi devices with active power/battery saving mode cause previous activity to lose it's state and when coming back for result it will call onCreate again so you won't get the true result.
Related
I have 3 activities say A, B and C.
A calls B.
When B doesn't call C it returns to A. But when B calls C it doesn't return to A, the app stops.
Now the real problem is, from activity A I want to call an image picker and crop the image. That's Activity B which crops and calls C for picking image.
Activity A:
iv_profile_pic.setOnClickListener(new View.OnClickListener() {//iv_profile_pic is an ImageView
#Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,profile_pic_chooser.class);
i.setFlags(0);
MainActivity.this.startActivityForResult(i, 999);
Toast.makeText(getApplicationContext(),"Reached",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 999) {
Bitmap image=data.getParcelableExtra("picture");
iv_profile_pic.setImageBitmap(image);
}
}
Activity B:
It has 2 buttons. Load and Crop. Load when clicked calls ImageChooserIntent and chooses an image which is opened in B with guidlines to crop.
Crop when clicked should return back to A the cropped image.
If crop is called without calling load, it returns to A with null, of-course.
But if Load is clicked first and then Crop is called, the app simply stops.
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null) {
mCropImageView.setImageBitmap(cropped);
iv.setImageBitmap(cropped);
Intent returnIntent = new Intent();
returnIntent.putExtra("picture", cropped);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
}
#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);
}
}
}
I got a workaround. The most probable problem I was facing was:
I was using an external library for cropping the image. This library did 2 things.
First, selected an image using imageChooser intent.
Second, Cropped that image.
After the library cropped the image, it wasn't saving the cropped image in local/external storage. But I was trying to pass it back to parent directory.
There's the problem. The file doesn't exist and still I am trying to use it. The application terminates.
So my workaround was,
• Save the bitmap in storage
• Pass the Uri to parent
• Extract that Uri from child
• Make bitmap from that Uri
• Apply on the ImageView
So Activity B had:
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null) {
mCropImageView.setImageBitmap(cropped);
iv.setImageBitmap(cropped);
File externalStorageDirectory = Environment.getExternalStorageDirectory();
externalStorageDirectory= new File(externalStorageDirectory , "FOLDERNAME");
if(!createDirIfNotExists(externalStorageDirectory)){
Toast.makeText(this,"Failed creating Directory!",Toast.LENGTH_SHORT).show();
}else{
File filename=new File(externalStorageDirectory, String.valueOf(Calendar.getInstance().getTimeInMillis())+".PNG");
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
cropped.compress(Bitmap.CompressFormat.PNG, 100, out); // cropped is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
Intent returnIntent = new Intent();
returnIntent.putExtra("picture", Uri.fromFile(filename));
setResult(RESULT_OK, returnIntent);
finish();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Toast.makeText(this,mCropImageUri.toString(),Toast.LENGTH_SHORT).show();
}
And Activity A had:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 999 && resultCode==RESULT_OK) {
Uri path=data.getParcelableExtra("picture");
Bitmap bitmap=null;
try {
bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), path);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this,path.toString(),Toast.LENGTH_SHORT).show();
if (bitmap!=null){
iv_profile_pic.setImageBitmap(bitmap);
}
}
Maybe my problem statement is wrong, but workaround works. Any edits/suggestions
are 100% welcome. Just in-case someone like me gets stuck, this might help!
I have created fragment with multiple image addition dialog. Each image can be added via camera or gallery. In both situations I can add only one image - after dismissing gallery/camera view application stops responding.
That's how I create camera and gallery pick intent:
//permissions request in other methods
private void pickImage() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_GALLERY);
}
private void openCamera() {
if (PermissionsHelper.checkStoragePermissions(ReportFragment.this)) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
fileFromCamera = fileUri.getPath();
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePicture, SELECT_PHOTO);
} else {
PermissionsHelper.requestStoragePermissions(this, CAMERA_STORAGE_PERMISSION_REQUEST);
}
}
Here is how result handled:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == SELECT_GALLERY) {
Uri selectedImageAddress = data.getData();
addPathsIfUnique(getRealPathFromURI(selectedImageAddress));
}
if (requestCode == SELECT_PHOTO) {
if (PermissionsHelper.checkStoragePermissions(this)) {
if(fileFromCamera != null) {
addPathsIfUnique(fileFromCamera);
}
} else {
PermissionsHelper.requestStoragePermissions(this, CAMERA_STORAGE_PERMISSION_REQUEST);
}
}
}
private void addPathsIfUnique(String path) {
if(path == null)
return;
for(String currentPath : photoPaths) {
if(currentPath.equals(path)) {
return;
}
}
photoPaths.add(path);
shopChanged(point);
}
In the shopChanged function I'm recreating ListView cells. I was also trying to completely remove ListView, replace it with single button in fragment, but result was same: after second time opened gallery or camera closed, application becomes not responding. Even OnResume breakpoint not fired. But after first opening all works good.
What can be reason for this behaviour?
Found a solution: this is new Google Play Services bug - issue fixed after downgrade to 8.4.0. Will search they bugtracker and submit bug, if it isn't submitted already
I'm working on an app which allows user to choose a picture from gallery and then I start a activity to crop it.
I want to send the cropped image back to calling activity.
Both activities extend AppCompatActivity.
Calling activity:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
// start image crop activity
String dataString = data.getDataString();
Intent intent=new Intent(this, CropPhotoActivity.class);
intent.putExtra("SELECTED_PICTURE_FOR_CROP", dataString);
startActivityForResult(intent, CROP_PICTURE);
}
else if(requestCode == CROP_PICTURE) {
// get cropped bitmap
Bitmap bitmap = (Bitmap) data.getParcelableExtra("CROPPED_IMAGE");
profilePhoto.setImageBitmap(bitmap);
}
}
}
In the crop image activity, I have a button, which on click should return back to calling activity:
Button okButton = (Button)findViewById(R.id.ok_button);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE", cropped_bitmap);
setResult(RESULT_OK, returnIntent);
finish(); // sometimes restarts app
}
});
Sometimes the bitmap gets returned correctly whereas sometimes it does not and the app gets restarted without error. Why is this happening? Does putExtra have anything to do with bitmap size or anything else?
You could try substituting
AppcompatActivity.this.finish()
(where AppcompatActivity is your class name)
for:
finish(); // sometimes restarts app
Or, create a method in the calling Activity:
public static void cropComplete(Activity activity)
{
activity.startActivity(activity, AnotherActivity.class);
activity.finish();
}
Theres's a limit for data length passed as extra in a intent. Try not passing the dataString value; instead you should save the image as a temporary file, pass the path in the intent and then load the image from your calling activity (or you can just save the dataString in a static helper class).
In the crop activity (saving bitmap code from Save bitmap to location):
// Save bitmap
String filename = "tempImage.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Get image file path
String path = dest.getAbsolutePath();
// Set result with image path
Intent returnIntent = new Intent();
returnIntent.putExtra("CROPPED_IMAGE_PATH", path);
setResult(RESULT_OK, returnIntent);
finish();
In the caller activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CROP_PICTURE) {
// Get image file path
String imagePath = data.getStringExtra("CROPPED_IMAGE_PATH");
// Load image
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}
i'm trying to take picture and save it to a file by using startActivityForResult(). But after tapping "Save" button it did not save anything and again opening the camera.
Using device Samsung Galaxy S3(4.1.1) and Samsung Galaxy Nexus(4.1.1) but its woking fine with Motorola Defy(2.3.4).
Is it the issues with Android OS 4.1.1 or Device ?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File file = null;
Date date = new Date();
try {
file = new File("photosearch-"+date.getTime()+".jpeg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
Log.e(TAG, " startActivityForResult");
startActivityForResult(intent, CAMERA_ACTIVITY);
} catch (Exception e) {
Log.d(TAG, ""+e);
//Check if sdcard is accessible
Toast.makeText(getActivity(), "Unable to access SD Card", Toast.LENGTH_LONG).show();
getActivity().finish();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult....");
if(resultCode == Activity.RESULT_CANCELED){
Intent intent = new Intent(getActivity(), AnotherListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
getActivity().finish();
}
if(resultCode == CAMERA_ACTIVITY){
Log.d(TAG, "It should come here..");
}
}
you have problem in you Extra Parameter, use this example here
I just want to take a Foto with my cam -(that functions)
To use it further i need the path were the intent has saved the picture.
But I don't want to tell the Intent where it should put the File.
(Because now it just creates the file automatically.
Heres the function that starts the camera
public void doCam() {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
// startActivityForResult(intent,0);
try {
startActivityForResult(i, TAKEPICTURE_ACTIVITY);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not available",
Toast.LENGTH_SHORT).show();
}
// Log.e(TAG, "Error in taking picture");
}
and heres the getting of the results and I want in the string address the path with the name of the picture
I found different solutions already but the all involved choosing the filename before taking the picture -> so the app decided how the picutre will be named.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKEPICTURE_ACTIVITY) {
// super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
//doesn't work
String address= (String) extras.get("EXTRA_OUTPUT");
The path should be found in intent.getData() try it.. If you don't have it there then you should consider forcing the camera to save the video in a custom location..
This is how you can get the path of the recently captured image:
try{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch(Exception e){
e.printStackTrace();
}
And in the onActivityResult() method:
String path=null;
try{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
path=getLastImagePath();
} catch(Exception e){
}