I am trying to store camera captured images at separate folder using below code but when i execute this code i am getting exception and i tried lot for getting solution but no use can some one help me please
android.os.FileUriExposedException: file:///storage/emulated/0/MyRamImages/FILENAME.jpg exposed beyond app through ClipData.Item.getUri()
code:-
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "FILENAME-"+ n +".jpg";
File image = new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 100);
First just capture the image then in onActivityResult get the image as bitmap then save that to the path you want to save.
private void openCamera()
{
// Start the camera and take the image
// handle the storage part in on activity result
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_IMAGE_REQUEST_CODE);
}
And inside on activity result method write the following code.
if (requestCode == CAPTURE_IMAGE_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
Bitmap imgBitmap = (Bitmap) data.getExtras().get("data");
File sd = Environment.getExternalStorageDirectory();
File imageFolder = new File(sd.getAbsolutePath() + File.separator +
"FolderName" + File.separator + "InsideFolderName");
if (!imageFolder.isDirectory())
{
imageFolder.mkdirs();
}
File mediaFile = new File(imageFolder + File.separator + "img_" +
System.currentTimeMillis() + ".jpg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
imgBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
fileOutputStream.close();
}
}
This works for me in 7.1.1 and lower versions as well.
Instead of return Uri.fromFile(mediaFile);
do
return FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
mediaFile);
That would require you to add a provider to the AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
And then create a provider_paths.xml file in xml folder under res folder.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Once refer this https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en