Seviel Seviel - 2 months ago 5
Android Question

Can't save a photo captured with standard camera app

I'm trying to take a photo with standard camera app and save it to a storage visible only to my app.

public void startCamera(View view)
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
File imageFile = null;

try
{
imageFile = createImageFile();
}
catch (IOException ex)
{
ex.printStackTrace();
}

if(imageFile != null)
{
Uri imageUri = FileProvider.getUriForFile(this, "vasiljevic.filip.secretnotes", imageFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, 1);
}
}
}


createImageFile method:

private File createImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyddMM_HHmmss").format(new Date());
EditText editText = (EditText) findViewById(R.id.txtNoteName);
String noteName = editText.getText().toString();
String imageFileName = noteName + "_" + timeStamp;
File storageDir = new File(getFilesDir(), "images");
if(!storageDir.exists())
{
storageDir.mkdir();
}

File image = File.createTempFile(imageFileName, ".jpg", storageDir);

return image;
}


This is part of the manifest containing FileProvider:

<provider
android:authorities="vasiljevic.filip.secretnotes"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>


And file_paths.xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
</paths>


After I take a photo, it displays the message "camera has stopped" if I run it on the emulator or "gallery has stopped" if I run it on real device. Later if I try to access it with ACTION_VIEW intent it says "can't open image" if I try it on a real device or if I try it on emulator it just behaves as if it had opened an image but the screen is all black and no real image is displayed.

Am I doing it right? is this code supposed to save the image properly? It's mostly based on Taking photos simply official android tutorial: Taking photos simply

Answer

Add FLAG_GRANT_WRITE_URI_PERMISSION to the Intent. Right now, your third-party app has no rights to save the photo to your Uri.

If you are supporting older than Android 5.0, you might also need to use a ClipData workaround, as Intent flags do not affect EXTRA_OUTPUT on older Android versions.

Comments