Camera Intent returns null onActivityResult
Asked Answered
P

5

7

I am trying to take a photo and to save it to a custom location-

public void SavePhoto(View view){

    Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    File imagesFolder = new File(Environment.getExternalStorageDirectory(), "WorkingWithPhotosApp");
    imagesFolder.mkdirs();

    File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
    Uri uriSavedImage = Uri.fromFile(image);

    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
    startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(data==null){
        Toast.makeText(MainActivity.this, "Data is null", Toast.LENGTH_SHORT).show();
    }
    else{
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            ImageView mImageView=(ImageView)findViewById(R.id.imageView);
            mImageView.setImageBitmap(imageBitmap);
        }
    }
}

data is null in onActivityResult(). What did I miss?

Ponderable answered 4/6, 2016 at 9:23 Comment(3)
Did you try my solution?Erinerina
You supplied EXTRA_OUTPUT. Hence, extras.get("data") is supposed to be null. Your photo, if it exists, will be at the location that you specified in EXTRA_OUTPUT. See github.com/commonsguy/cw-omnibus/tree/master/Camera/Content for one using files and github.com/commonsguy/cw-omnibus/tree/master/Camera/… for one using FileProvider.Giavani
please check if are using build sdk 23 above need to handle run-time permissions for read& write SD cardElayne
S
5

Your preinsert a uri here:

 imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

So when you get a Activity.RESULT_OK just load the taken photo by its known url. Then you can set the path onActivityResult like below but you need to convert in to Bitmap.

if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
           // Convert here your uri to bitmap then set it.//
            mImageView.setImageBitmap(YOUR_BITMAP);
 }
Shut answered 4/6, 2016 at 9:36 Comment(3)
I tried Bitmap myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath()); But still ImageView does not show the photo.Ponderable
First you need to save photo in onActivityResult.Shut
Why is this good practice? How do you know that you are getting the right camera result back?Interceptor
E
1

File imagesFolder = new File(Environment.getExternalStorageDirectory(), "WorkingWithPhotosApp");

I think you need to check first either your directory exists or not. This is how I performed this task. In my case I am creating a folder in default DCIM directory.

private void dispatchTakePictureIntent(int actionCode) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File f = null;
            try {
                f = setUpPhotoFile();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            } catch (IOException e) {
                e.printStackTrace();
                f = null;
            }
    startActivityForResult(takePictureIntent, actionCode);
    }

private File setUpPhotoFile() throws IOException {
        File f = createImageFile();
        return f;
    }

private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "IMG_" + timeStamp + "_";
        File albumF = getAlbumDir();
        File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
        return imageF;
    }

private File getAlbumDir() {
        File storageDir = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            storageDir = getAlbumStorageDir(PHOTO_ALBUM_NAME);
            if (storageDir != null) {
                if (! storageDir.mkdirs()) {
                    if (! storageDir.exists()){
                        Log.d("Camera", "failed to create directory");
                        return null;
                    }
                }
            }
        } else {
            Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
        }
        return storageDir;
    }

public File getAlbumStorageDir(String albumName) {
        return new File (
                Environment.getExternalStorageDirectory()
                        + "/dcim/"
                        + albumName);
    }

Hope this helps!

Erinerina answered 4/6, 2016 at 9:45 Comment(0)
R
0

Try like this :

if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
       Strng imagePath = uriSavedImage.getPath(); // uriSavedImage - make it global
}
Raddled answered 4/6, 2016 at 9:30 Comment(0)
B
0

I had the same problem , like you, so I decided implement the solution given here

Then, in my own project, I did that

First : Create the provider in the manifest, the same that the guide says.
Second : Create a class name LegacyCompatCursorWrapper (ps. see the guide or contact with me , I can send the code), you need this class ,in the follow step.
Third : Create this class LegacyCompatFileProvider
Fourth: Before to do that

startActivityForResult(takePictureIntent, actionCode);

Implement this

 Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Uri outputUri=FileProvider.getUriForFile(this, AUTHORITY, output);

    i.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);

    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
        i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    }
    else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN) {
        ClipData clip=
                ClipData.newUri(getContentResolver(), "A photo", outputUri);

        i.setClipData(clip);
        i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    }
    else {
        List<ResolveInfo> resInfoList=
                getPackageManager()
                        .queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);

        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            grantUriPermission(packageName, outputUri,
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
    }

    try {
        startActivityForResult(i, CONTENT_REQUEST);
    }
    catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.msg_no_camera, Toast.LENGTH_LONG).show();
        finish();
    }

So in onActivityResult()

  if (requestCode == CONTENT_REQUEST) {
          //  if (resultCode == RESULT_OK) {
                Intent i=new Intent(Intent.ACTION_VIEW);
                Uri outputUri=FileProvider.getUriForFile(this, AUTHORITY, output);

                i.setDataAndType(outputUri, "image/jpeg");
                i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Bitmap thumbnail = null;
                Bundle extras = i.getExtras();
            try {
                thumbnail = MediaStore.Images.Media.getBitmap(this.getContentResolver(),outputUri );
            } catch (IOException e) {
                e.printStackTrace();
            }
            mImageProfile.setImageBitmap(thumbnail);
            saveImage(thumbnail);
 }

Where mImageProfile --> is an ImageView on the View. Remember, that is according the guide.

Bearable answered 13/12, 2017 at 10:28 Comment(0)
A
0

I have had this problem in Kotlin and Understood it is null when you are using intent to open camera . if you need to filter your code with the value of intent you should define the data that you need for example if you need pictures Uri should define this as global value :

1- private var resultUri: Uri? = null

then initial it in every method you are taking pic like this :

2- resultUri = requireActivity()!!.contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues() )

then in onActivityResult method you can use the value of it and continue your process.I hope it will be clear

Avifauna answered 27/7, 2022 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.