Reputation: 3
I have a DialogFragment which pops up to ask the user to select to choose to take a picture, or select one from the gallery. When I open the gallery and select an image, nothing happens and OnActivityResult Doesn't respond. Is it because the DialogFragment class shuts down soon after an image is selected and doesn't have time to go through the OnActivityResult class?
Here is the onCreateDialog for the DialogFragment Class:
public class PhotoFragment extends DialogFragment {
public static final int SELECT_PHOTO = 100;
public Bitmap image;
public static interface OnCompleteListener {
public abstract void onComplete(Bitmap image);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setItems(new CharSequence[]
{"Take a Photo", "Select Image From Gallery"},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
break;
case 1:
doToast("Picking Image",true);
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , SELECT_PHOTO);//one can be replaced with any action code
break;
}
}
});
return builder.create();
}
Here is the code for the activityOnResult() (located in the same class, PhotoFragment.java)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
onActivityResult(requestCode, resultCode, imageReturnedIntent);
doToast("Activity Result", true);
switch (requestCode) {
case SELECT_PHOTO:
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContext().getContentResolver().openInputStream(imageReturnedIntent.getData());
} catch (FileNotFoundException e) {
doToast("Input Stream not found", true);
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image = yourSelectedImage;
}
}
Upvotes: 0
Views: 1148
Reputation: 1177
Add on onActivityResult in your activity and then get the fragment and call the fragment onActivityResult. Example:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
fragment.onActivityResult(requestCode, resultCode, data);
}
Upvotes: 0