0

I am making an Android app that can take a picture and save it to the gallery. However, after taking the picture and tapping on the checkmark, the camera intent dismisses but the app is closed and the picture is not saved.

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    String imageName = "Blah.jpg";
    File imageFile = new File(pictureDirectory, imageName);
    Uri pictureUri = Uri.fromFile(imageFile);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
    startActivityForResult(cameraIntent,1313);

The intent successfully launches but the following is never called and the app just closes:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1313 && resultCode == RESULT_OK) {
        //...
    }
}
Schuey999
  • 4,706
  • 7
  • 21
  • 36
  • are you using nougat?? – Santanu Sur Feb 12 '18 at 18:52
  • @SantanuSur I am using API 27 on the emulator. – Schuey999 Feb 12 '18 at 18:53
  • The [android-studio] tag should only be used for questions about the tool itself, not for questions about general Android programming. Please see: [How do I avoid misusing tags?](https://meta.stackoverflow.com/questions/354427/how-do-i-avoid-misusing-tags) – EJoshuaS - Stand with Ukraine Feb 12 '18 at 18:56
  • @EJoshuaS Sorry. – Schuey999 Feb 12 '18 at 18:56
  • "but the app is closed" -- what is "the app"? The camera app? Your app? Some other app? Note that `Uri.fromFile()` will not work on Android 7.0+. You will need to use `FileProvider` or a similar option. [This sample app](https://github.com/commonsguy/cw-omnibus/tree/v8.9/Camera/FileProvider) demonstrates how to use `ACTION_IMAGE_CAPTURE` with `FileProvider`. – CommonsWare Feb 12 '18 at 18:57
  • @CommonsWare My app closes. The camera app closes (as it should) but also closes my app. – Schuey999 Feb 12 '18 at 18:58
  • lel i have updated my answer .. – Santanu Sur Feb 12 '18 at 19:00
  • 1
    "The camera app closes (as it should) but also closes my app" -- if by "closes my app", you mean that your app is crashing, use LogCat to examine the Java stack trace associated with your crash. If by "closes my app" you mean "the home screen appears", that may be a bug in the camera app that you are using, as some camera apps have lightly-tested `ACTION_IMAGE_CAPTURE` support. And if "closes my app" you mean something else, please explain what you mean. – CommonsWare Feb 12 '18 at 19:03
  • The home screen appears. I'm just using the default camera app in the emulator – Schuey999 Feb 12 '18 at 19:07

1 Answers1

0

You need to use FileProvider for obtaining file URI and add grant the intent flag for reading URI... for above nougat) follow these steps .. android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Santanu Sur
  • 10,997
  • 7
  • 33
  • 52