onActivityResult has data null for startActivityForResult in fragment - android

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) {

Related

How to open gallery (not letting the user choose between Gallery to Photo apps)

I tried this:
Intent getIntent = new Intent(Intent.ACTION_PICK);
getIntent.setType("image/*");
startActivityForResult(Intent.createChooser(getIntent, getString(R.string.select_image)), REQUEST_CODE_PICK_IMAGE);
but it lets me choose which app to open (Gallery/Photo/File Explorer) and I want it to open Gallery.
I also tried this but no success:
Intent getIntent = new Intent(Intent.CATEGORY_APP_GALLERY);
getIntent.setType("image/*");
Here is sample code for open gallery from app.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_IMAGE);
OnActivityResult for get image.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getActivity(), "Canceled", Toast.LENGTH_SHORT).show();
}
}
}

getStringExtra() return null

I try to send extra data of string by intent to a function, but I receive null.
here is the intent.put:
private void takePicFromGallery(String nameOfButton) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
**intent.putExtra(NAME_OF_BUTTON, nameOfButton.toString());**
startActivityForResult(intent.createChooser(intent, "choose picture"), PICK_FROM_GALLERY);
and here is the the getting:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String nameOfButton = data.getStringExtra(NAME_OF_BUTTON);
switch (nameOfButton) {
case "ibMainPicture": {
ibMainPicture.setImageBitmap(bitmap);
break;
}
case "imageButton1": {
imageButton1.setImageBitmap(bitmap);
break;
}
The intent received during onActivityResult is not the same intent which you are creating in the takePicFromGallery method. The intent you are starting is consumed by the Activity opened and it sends a new intent back to your application.
Option1(Preferred Option):
private static final int IB_MAIN_PICTURE_REQUEST_CODE = 524;
private static final int IMAGE_BUTTON_1_REQUEST_CODE = 785;
private void takePicFromGallery(String nameOfButton) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if(nameOfButton.equals("ibMainPicture")) {
startActivityForResult(intent.createChooser(intent, "choose picture"), IB_MAIN_PICTURE_REQUEST_CODE);
else if(nameOfButton.equals("imageButton1") {
startActivityForResult(intent.createChooser(intent, "choose picture"), IMAGE_BUTTON_1_REQUEST_CODE);
}
Then when getting the Result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
if(requestCode == IB_MAIN_PICTURE_REQUEST_CODE) {
ibMainPicture.setImageBitmap(bitmap);
} else if(requestCode == IMAGE_BUTTON_1_REQUEST_CODE) {
imageButton1.setImageBitmap(bitmap);
}
}
}
Option 2:
private static String lastButtonClicked = null;
private void takePicFromGallery(String nameOfButton) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
lastButtonClicked = nameOfButton.toString();
startActivityForResult(intent.createChooser(intent, "choose picture"), PICK_FROM_GALLERY);
}
Then when getting the Result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(lastButtonClicked == null || resultCode != Activity.RESULT_OK || requestCode != PICK_FROM_GALLERY) {
return;
}
switch (lastButtonClicked) {
case "ibMainPicture": {
ibMainPicture.setImageBitmap(bitmap);
break;
}
case "imageButton1": {
imageButton1.setImageBitmap(bitmap);
break;
}
...
}
Use a specific request code for each different button clicks instead of a generic PICK_FROM_GALLERY, then in the onActivityResult you can check the request code sent with the intent

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.

how to capture image from camera, in fragment,

I am new to Android, and I have done lots of training but the image does not load from the camera. Below is my code for capturing image from camera or gallery:
public void showDiloag(){
Dialog dialog = new Dialog(getActivity());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Image Source");
builder.setItems(new CharSequence[] { "Gallery", "Camera" },
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
switch (which) {
case 0:
Intent intent = new Intent(
Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent
.createChooser(
intent,
"Choose a Picture");
getAcitivity.startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
break;
case 1:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
cameraIntent,
ACTION_REQUEST_CAMERA);
break;
default:
break;
}
}
});
builder.show();
dialog.dismiss();
}
And for display that photo:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("OnActivityResult");
if (resultCode == getActivity().RESULT_OK) {
if (requestCode == Utils.ACTION_REQUEST_GALLERY) {
// System.out.println("select file from gallery ");
Uri selectedImageUri = data.getData();
String tempPath = JuiceAppUtility.getPath(
selectedImageUri, getActivity());
Bitmap bm = JuiceAppUtility
.decodeFileFromPath(tempPath);
imgJuice.setImageBitmap(bm);
} else if (requestCode == Utils.ACTION_REQUEST_CAMERA) {
Bitmap photo = (Bitmap) data.getExtras()
.get("data");
imgJuice.setImageBitmap(photo);
}
}
}
Also image is captured from camera and choose from gallery but it will not load in ImageView. Can anybody help me please?
Ya i found your problem
just remove below line and
getAcitivity.startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
and write down below code
startActivityForResult(
chooser,
ACTION_REQUEST_GALLERY);
just remove getActivity
FRAGMENT SIDE
btnimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
private void showPictureDialog(){android.app.AlertDialog.Builder pictureDialog = new android.app.AlertDialog.Builder(getActivity());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// choosePhotoFromGallary();
choosePhotoFromGallary();
break;
case 1:
// takePhotoFromCamera();
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void takePhotoFromCamera() {
Uri resultUri;
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
resultUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, resultUri);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent, 22);
}
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 11);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK)
{
if (requestCode == 11) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
// String path = saveImage(bitmap);
// Toast.makeText(getActivity(), "Image Saved!", Toast.LENGTH_SHORT).show();
iv_froncnic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
{
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
}
}
}
In parent ACTIVITY
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode==this.RESULT_OK){
super.onActivityResult(requestCode, resultCode, data);
setResult(RESULT_OK, data);
}
}

onCreate called after onActivityResult when I pick picture from gallery

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(...)

Categories

Resources