onCreate called after onActivityResult when I pick picture from gallery - android

I have 'SherlockFragmentActivity' with overrided 'onActivityResult'.
I try to get image from camera and gallery and crop it.
The problem is I returned on my activity not fragment after onActivityResult called.
...
FragmentTransaction t = fragmentManager.beginTransaction();
LogInFragment logFrag = new LogInFragment();
t.replace(R.id.fragment_container, logFrag);
t.commit();
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
Activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:background="#color/textWhite"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
And I also have 'SherlockFragment' where I picked image:
startImagePickerDialog(this);
public void startImagePickerDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(getSherlockActivity());
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("noFaceDetection", true);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), Const.GALLERY_PICTURE);
} catch (ActivityNotFoundException e) {
Log.e(LOG_TAG, "ActivityNotFoundException");
}
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("noFaceDetection", true);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, Const.CAMERA_REQUEST);
} catch (ActivityNotFoundException e) {
Log.e(LOG_TAG, "ActivityNotFoundException");
}
}
});
myAlertDialog.show();
}
And 'onActivityResult' in 'SherlockFragment':
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != getSherlockActivity().RESULT_OK) {
Log.e(LOG_TAG, "resultCode != RESULT_OK");
return;
}
if (requestCode == Const.CAMERA_REQUEST) {
Log.d(LOG_TAG, "requestCode == CAMERA_REQUEST");
Bundle extras = data.getExtras();
if (extras != null) {
Log.d(LOG_TAG, "extras != null");
Bitmap photo = extras.getParcelable("data");
icon.setImageBitmap(photo);
}
}
if (requestCode == Const.GALLERY_PICTURE) {
Log.d(LOG_TAG, "requestCode == GALLERY_PICTURE");
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Log.d(LOG_TAG, "extras != null");
Bitmap photo = extras2.getParcelable("data");
icon.setImageBitmap(photo);
}
}
}
UPDATE
When I call camera activity my main activity call 'onSaveInstanceState' and after that 'onRestoreInstanceState'. Is it a reason?

Check your "Settings" -> "Developer options" -> "Don't keep activities" flag.
This is the nature of android if your device needs memory it destroys activities which are not visible. So you have to consider that your activity can be recreated any time. BTW "Don't keep activities" option is there to simulate your application when your device needs memory and destroys your backstack activities.

Try Like this
Change
Bitmap photo = extras.getParcelable("data");
To
Bitmap photo=(Bitmap) intent.getExtras().get("data");
Edited:-
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != getSherlockActivity().RESULT_OK) {
Log.e(LOG_TAG, "resultCode != RESULT_OK");
return;
}
if (requestCode == Const.CAMERA_REQUEST) {
Log.d(LOG_TAG, "requestCode == CAMERA_REQUEST");
Bitmap photo=(Bitmap) intent.getExtras().get("data");// Changed Here
icon.setImageBitmap(photo);
}
if (requestCode == Const.GALLERY_PICTURE) {
Log.d(LOG_TAG, "requestCode == GALLERY_PICTURE");
Uri imageUri= intent.getData();// Changed Here, or first decode the image to Avoid OutOfMemory Error
icon.setImageURI(imageUri);
}
}

Please replace
frag.startActivityForResult(...);
In your fragment with
startActivityForResult(...)

Related

Image cropping is not working in android 7.0 and higher version

I want to capture profile image from camera and crop. In our code camera image is working but cropping is not working.
Camera method
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
outputFileUri = ProviderUtil.getOutputMediaFileUri(getActivity().getBaseContext());
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
Crop Image method
public void cropCapturedImage() {
try {
getActivity().grantUriPermission("com.ht.msb.mysocialbuy.provider",outputFileUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(outputFileUri, "image/*");
CropIntent.putExtra("crop", "true");
if (imagebrowseType == 1) {
CropIntent.putExtra("outputX", 400);
CropIntent.putExtra("aspectX", 1);
CropIntent.putExtra("aspectY", 1);
} else {
CropIntent.putExtra("outputX", 600);
CropIntent.putExtra("aspectX", 6);
CropIntent.putExtra("aspectY", 4);
}
CropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
CropIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
CropIntent.putExtra("outputY", 400);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
CropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(CropIntent, PIC_CROP);
} catch (ActivityNotFoundException e) {
Log.e("error_crop",e.toString()+" 1");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
if (outputFileUri != null) {
cropCapturedImage();
}
} else if (requestCode == PIC_CROP) {
try {
Bitmap thePic;
if (data != null) {
thePic = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), outputFileUri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
}
} catch (Exception e) {
Log.e("error", e.toString() + "");
}
}
}
}
Android does not have an image-cropping Intent.
You should add a library to your project that handles image cropping, then use that library with the image that you get back from your startActivityForResult() call.
in onActvityResult method change your code like:
if (requestCode == PIC_CROP) {
if (data != null) {
// get the returned data
// get the cropped bitmap
if (data.getExtras()!=null) {
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
imgPhoto.setImageBitmap(selectedBitmap);
}
}
}
Or, Use uCrop library which makes things easier.

How take a picture with a Fragment (Android Studio)

I'm trying to take a picture in gallery, so i know do this in Activity, i use a Intent to call the gallery, and onActivityResult for take the path, but when i use a Fragment, i cannot to use "onActivityResult", can someone give a example of it using a Fragment and CustomDialog?
Inside your fragment write this code
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// ******** code for crop image
i.putExtra("crop", "true");
i.putExtra("aspectX", 100);
i.putExtra("aspectY", 100);
i.putExtra("outputX", 256);
i.putExtra("outputY", 356);
try {
i.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(i, "Select Picture"), 0);
}catch (ActivityNotFoundException ex){
ex.printStackTrace();
}
In you Main Activity of the fragment write this code onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==0 && resultCode == Activity.RESULT_OK){
try {
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
img_user.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try with this, it should work. Don't forget to accept the answer if correct.

onActivityResult has data null for startActivityForResult in fragment

I have a fragment where I am calling getActivity().startActivityForResult for camera activity and I have onActivityResult in my MainActivity to handle the Result.
Fragment
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 250);
intent.putExtra("outputY", 250);
try {
intent.putExtra("return-data", true);
getActivity().startActivityForResult(Intent.createChooser(intent,"Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
MainActivity
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) //CANCELED
{
Toast.makeText(this, "canceled", Toast.LENGTH_SHORT).show();
}
switch (requestCode) {
case PICK_FROM_GALLERY:
Toast.makeText(this, "Pick from Gallery", Toast.LENGTH_SHORT).show();
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Result Okay", Toast.LENGTH_SHORT).show();
Bundle extras2 = data.getExtras();
if (extras2 != null) {
//Doesn't enter here
} else {
Toast.makeText(this, "extra is null", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
Activity #Oncreate open camera intent
// Camera Option Clicked
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 1);
Handle onActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if(resultCode == RESULT_OK){
if (data != null) {
takePhoto(data);
}
}
break;
}
}
Display image on ImageView
private void takePhoto(Intent imageData){
Bundle extras = imageData.getExtras();
if(extras != null){
imageView.setImageBitmap((Bitmap) extras.get("data"));
}
}
change this line
getActivity().startActivityForResult(Intent.createChooser(intent,"Complete action using"), PICK_FROM_GALLERY);
to
startActivityForResult(Intent.createChooser(intent,"Complete action using"), PICK_FROM_GALLERY);
refer this for further information onActivityResult is not being called in Fragment
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
112);
if (requestCode == 112) {
try {
InputStream inputStream = getContentResolver()
.openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(
mFileTemp);
copyStream(inputStream, fileOutputStream);// do other stuff
fileOutputStream.close();
inputStream.close();
//do other stuff
} catch (Exception e) {
e.printStackTrace();
}
}
You should call
startActivityForResult(Intent.createChooser(intent,"Complete action using"), PICK_FROM_GALLERY); from your fragment and then implement the onActivityResult() in your Fragment itself, and in the onActivityResult() just check for the result code as
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_FROM_GALLERY) {

No Activity found to handle Intent act=com.android.camera.action.CROP

I'm trying to implement a function to pick a photo from android built-in gallery (not from SD card) or taking a photo using camera. After the image is picked it will be cropped by the user. An ImageView will also be updated with the cropped image. Now after picking an image from gallery, I cannot crop it -- "No Activity found to handle Intent act=com.android.camera.action.CROP" error was returned. And I also can't seem to update the ImageView with the selected image. Can someone please tell me what was wrong? Thanks.
My code is as follows:
private void ShowPickDialog() {
new AlertDialog.Builder(this)
.setTitle("Add Photo")
.setNegativeButton("Select from Photos", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),3);
}
})
.setPositiveButton("Take a Pic", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
.fromFile(new File(Environment.DIRECTORY_PICTURES,
"image.jpg")));
startActivityForResult(intent, 2);
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
startPhotoZoom(data.getData());
break;
case 2:
File temp = new File(Environment.getExternalStorageDirectory()
+ "/test.jpg");
startPhotoZoom(Uri.fromFile(temp));
break;
case 3:
if(data != null){
setPicToView(data);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
//update ImageView with selected image
mPic.setImageBitmap(photo);
}
}
Android Does Not Have a Crop Intent
you can use libraries instead
Android CropImage

Fragment getting closed after on activity result call

I have a fragments A and B. A contains a list and B has an imageview. when i click on a list item in fragment A it goes to B. I'm calling camera and gallery intent from B.
In B
alert.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, PICK_FROM_CAMERA);
} else if (item == 1) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, PICK_FROM_FILE);
} else {
dialog.cancel();
}
}
});
onActivityResult in B
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_CAMERA) {
if (resultCode == getActivity().RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
cameraIcon.setImageBitmap(bitmap);
} else if (resultCode == getActivity().RESULT_CANCELED) {
Toast.makeText(getActivity(), "Result has been cancelled!",
Toast.LENGTH_LONG).show();
}
} else if (requestCode == PICK_FROM_FILE) {
try {
if (resultCode == getActivity().RESULT_OK) {
try {
stream = getActivity().getContentResolver()
.openInputStream(data.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap = BitmapFactory.decodeStream(stream);
cameraIcon
.setImageBitmap(Bitmap.createScaledBitmap(bitmap,
bitmap.getWidth() / 2,
bitmap.getHeight() / 2, true));
} else if (resultCode == getActivity().RESULT_CANCELED) {
Toast.makeText(getActivity(), "Result has been cancelled!",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}
But some times after the intent collects the image and comes to onActivityResult fragment B
get closed and goes to fragment A instead of setting the image to the image view in fragment B.....
What am i doing wrong please help
Please check using another device.I think the device issue.
Just a guess, but I would say an exception is being thrown in fragment B after onActivityResult has finished.. perhaps you should check your event log/trace the events in the onResume/createView etc.

Categories

Resources