MichelReap
MichelReap

Reputation: 5770

Capture image with camera using FileProvider, how to store uri

I have followed tutorials such as this, this or this about how to use FileProvider to take a picture with the camera and store it on a temp file for later upload.

They all generate a file, get the uri using file provider, and then call the CAmera intent with this uri:

 val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        if (uri != null) {
            try {
                if (intent.resolveActivity(activity.packageManager) != null) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                    activity.startActivityForResult(intent, resultCode)
                }
            } catch (t: Throwable) {
                Timber.e(t, t.message)
            }
        }

Then on onActivityResult they get the image using:

 @Override
protected void onActivityResult(int requestCode, int resultCode,
                                              Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE) {
           //don't compare the data to null, it will always come as  null because we are providing a file URI, so load with the imageFilePath we obtained before opening the cameraIntent
        Glide.with(this).load(imageFilePath).into(mImageView);   
        // If you are using Glide.
    }
}

So to quote this tutorial "load with the imageFilePaht we obtained before opening the cameraIntent".

For the most part it works, but when I try with the emulator for some reason my activity is destroyed when the camera app is launched (probably low memory) and my reference of the Uri is null when I come back from the camera.

Can I retrieve this Uri from the result of the activity? Or do I really have to store it in sharedpreferences or similar?

Upvotes: 1

Views: 2153

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007349

and my reference of the Uri is null when I come back from the camera

Save that Uri in your saved instance state Bundle of whatever activity or fragment is calling startActivity() to start the ACTION_IMAGE_CAPTURE app. See this sample app for a complete implementation of an ACTION_IMAGE_CAPTURE request that does this.

Upvotes: 2

Related Questions