On android devices below Nougat I have no problem saving images in the device's external storage and then storing the file path and displaying the image with Picasso.
However when tested on a Nougat device, I started getting FileUriExposedException whenever I start the camera intent.
I added fileprovider in manifest and also added a filepaths.xml
Manifest.xml:
<provider
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
android:name="android.support.v4.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
filepaths.xml:
<paths>
<external-path name="mediaimages" path="." />
</paths>
Here's my code
MainActivity.java
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String authorities = getPackageName() + ".fileprovider";
File image = getTempFile(AddListingPage2Activity.this);
try {
image.createNewFile(); //Getting ignore warning
} catch (IOException e) {
e.printStackTrace();
}
Uri imageUri = FileProvider.getUriForFile(AddListingPage2Activity.this, authorities, image);
mImageFileUri = imageUri;
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePicture, CAMERA_REQ);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_REQ:
if (resultCode == RESULT_OK) {
//How to get bitmap and create file to store in storage
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeFile(mImageFileUri.getPath()); //returns null
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageFileUri); //returns null as well
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
private File getTempFile(Context context) {
final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
if (!path.exists()) {
path.mkdir(); //Getting ignored warning
}
return new File(path, "myImage.jpg");
}
How do I save the image file and retrieve the file path in OnActivityResult?
I figured out why the camera app was unable to save the image. The app was supposed to save an image in ./packagename/myImage.jpg but myImage.jpg was created as a directory. After I deleted the folder and tried running the app, I was finally able to save the image.