Open Camera Intent with filepath android 11 not working - android

The open camera intent is not working in android 11, the app is getting crashed everytime, but the same code is tested and working in Android 6,7,8.
Below is the code --
private void openCameraIntent() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(pictureIntent.resolveActivity(getActivity().getPackageManager()) != null){
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.d("IOError", ex.getMessage());
} catch (Exception ex2) {
Log.d("Error", ex2.getMessage());
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(context.getApplicationContext(), getActivity().getPackageName()+".fileprovider", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(pictureIntent, 1);
}
}
}
String imageFilePath;
private File createImageFile() throws IOException {
String timeStamp =
new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
imageFilePath = image.getAbsolutePath();
Log.d("imageFilePath", imageFilePath);
return image;
}
Android menifest file --
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
file_paths.xml --
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--change only the package name if you have change the package name of app-->
<external-path name="my_images" path="AppName/Temp/" />
<external-path name="external_files" path="."/>
</paths>
What might be the changes required which i am missing. Please guide me to achieve the solution. Thank you.

Related

Saving image to gallery

I am building an application in which I want to capture an image using intent (MediaStore.ACTION_IMAGE_CAPTURE) and want to save it to gallery.
Every thing is working fine but image is not being saved to gallery.
I have followed google documentation (https://developer.android.com/training/camera/photobasics) to perform my task.
But image is not being saved to gallery.
My manifest file :
.
.
.
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.kartik.translater"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
.
.
my file_paths.xml file:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!-- <external-files-path name="my_images" path="Pictures" />-->
<!-- <external-path name="external_files" path="." />-->
<external-path
name="external"
path="."/>
<external-files-path
name="external_files"
path="."/>
<cache-path
name="cache"
path="."/>
<external-cache-path
name="external_cache"
path="."/>
<files-path
name="files"
path="."/>
</paths>
This set of instruction will trigger image capturing process:
//Capture Input Image
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
dispatchTakePictureIntent() definition :
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) == null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.kartik.translater",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
createImageFile() fn. definition:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
onActivityResult() defintion:
if(requestCode==CAMERA_REQUEST_CODE && resultCode==RESULT_OK)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.parse(currentPhotoPath);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
Toast.makeText(MainActivity.this, contentUri+"", Toast.LENGTH_SHORT).show();
}
** I am using Android 11 to run the app.
***Toast message of onActivityResult() is getting executed but image is not getting saved in gallery.
In order to be able to write to external storage on android 10+, you need to have access to it. To provide this capability in your app, use the ACTION_OPEN_DOCUMENT_TREE intent action.
More details can be found here: https://developer.android.com/training/data-storage/shared/documents-files?hl=ru#grant-access-directory

android 10 camera image issue

i am getting trying to get image from camera in android 10 but it is not working properly.i have used this code for getting image from camera
this is my intent
val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, createImageFile())
startActivityForResult(takePhotoIntent, 3)
her it is my file provider
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="images"
path="." />
</paths>
here it is my function to create file path
public static File createImageFile(
Context context,
String dirName,
String fileName,
String fileType) {
try {
File file = createDir(context, dirName);
File image = new File(file.getAbsoluteFile() + File.separator + fileName + fileType);
if (!image.getParentFile().exists()) {
image.getParentFile().mkdirs();
}
image.createNewFile();
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here it is file provider define in manifest file
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.android.restuarantuser.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>

FileProvider.getUriForFile doesn't save image to gallery and can't access file OnActivityResult

In my app, trying to capture images using the camera app.
I am updating my app to use FileProvider.getUriForFile when specifying the file path to save images to, as Uri.fromFile is deprecated.
It was working fine beforehand using Uri.fromFile. But I can't get it to work using FileProvider.getUriForFile.
I am creating the image file as follows:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
Then, depending on the target sdk, I get the image URI:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
jobImageURI = Uri.fromFile(photoFile);
} else {
jobImageURI = FileProvider.getUriForFile(OrderDetails.this, BuildConfig.APPLICATION_ID + ".provider",photoFile);
}
I have updated the app manifest xml to include the provider, as per the android developer documentation.
I have a provider_paths.xml file which holds the path:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Then I launch the camera:
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, jobImageURI);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
However, after the photo is taken and it comes back to the onActivityResult function, I read back in the image file.
The image isn't saved to the Gallery, as I am reading back in the last file from the Gallery but it isn't there.
I can't access the file using the path from the jobImageURI above either.
Is the path I've provided the provider_paths.xml file incorrect, or why can't I access the images?
try this way
create a xml file under xml folder in res directory
provider_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"
path="Android/data/yourAppPackageName/files/Pictures" />
</paths>
Register Provider in AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="yourAppPackageName.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path"/>
</provider>
add these permissions
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.CAMERA"/>
on Camera Button Click call dispatchTakePictureIntent()
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.arantico.servicepro.provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
here mCurrentPhotoPath will show the path of file where it got stored

Failed to find configured root that contains ***(Path) - FileProvider Issue

I am in trouble with this issue, couldn't find any way out yet.
I have configured a Fileprovider in manifest.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.package.name.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
where the #xml/file_paths is like
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="my_images"
path="Android/data/com.package.name/files/Pictures" />
<external-files-path
name="my_images_" />
</paths>
And my java code is like below
private void selectImageFromCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.e("selectImageFromCamera", "Error: " + ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
try {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.package.name.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
} catch (Exception e) {
e.printStackTrace();
Log.e("selectImageFromCamera", "Error: " + e);
}
}
}
The method createImageFile()
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Log.e("storageDir", "storageDir: " + storageDir.getAbsolutePath());
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
myCurrentPhotoPath = image.getAbsolutePath();
return image;
}
But I am always getting problem when creating photoUri, to be exactly at below line.
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.package.name.fileprovider",
photoFile);
Error in try catch
.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.package.name/files/Pictures/JPEG_20170417_115925_834197983.jpg
Any help would be appreciated. Thanks.

Getting null pointer exception when trying to get the URI for a file

When the activity opens, a dialog window opens asking the user to either take a picture from the camera, or choose one from the gallery. As soon as I hit the button to open the camera, the app crashes and I get a Null Pointer exception related to getting the URI. I have been following Google's walkthrough for saving pictures form the camera and can't seem to find where the issue is.
Line where the error occurs:
Uri photoURI = FileProvider.getUriForFile(CreatePostActivity.this,
"xyz.beerme.beerme.provider",
photoFile);
Whole method:
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
} catch (IOException ex){
Snackbar message = Snackbar.make(findViewById(R.id.activity_create_post), "Error creating image", Snackbar.LENGTH_LONG);
message.show();
}
if(photoFile != null){
Uri photoURI = FileProvider.getUriForFile(CreatePostActivity.this,
"xyz.beerme.beerme.provider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
dialog.dismiss();
}
});
createImageFile method:
private File createImageFile() throws IOException{
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_beerme";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="xyz.beerme.beerme">
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:supportsRtl">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="redacted" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="xyz.beerme.beerme.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" ></meta-data>
</provider>
<activity android:name=".PostsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.categroy.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".CreatePostActivity"></activity>
</application>
</manifest>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/xyz.beerme.beerme/files/Pictures" />
</paths>
Try Below code for createImageFile method
private File createImageFile() {
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// path = path + (timeStamp + "1jpg");
try {
file = File.createTempFile(timeStamp, ".jpg", storageDir);
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24)
mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", file));
else
mCurrentPhotoPath = String.valueOf(Uri.fromFile(file));
return file;
}
In case anyone finds this in the future, I typed "provider" instead of "fileprovider". As provider does not exist, that is the source of the exception.

Categories

Resources