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>
Related
I am sharing the app with the file provider and I want to share the image from the bitmap.
I have two file providers number one is for share apk, number two for share image. apk file provider works good but the image share file provider not sharing images. if I share an image to WhatsApp, Gmail it says file format does not support it.
fileprovider.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-cache-path
name="apk"
path="/"/>
</paths>
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-cache-path name="img" path="my_images/"/>
</paths>
imagesharefrombitmap.kt
imgBtnShare.setOnClickListener {
shareImage()
loadingDialoglordshiva.startDialog()
}
}
private fun shareImage() {
val bitmapShare = getBitmapFromView(relLayout)
val filename = "${System.currentTimeMillis()}.jpg"
val cachePath = File(externalCacheDir.toString() + "/my_images")
cachePath.mkdirs()
//create a png file
//create png file
val file = File(cachePath, filename)
val fileOutputStream: FileOutputStream
try {
fileOutputStream = FileOutputStream(file)
bitmapShare.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
fileOutputStream.flush()
fileOutputStream.close()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
val myImageFileUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider_paths",file)
//create a intent
//create a intent
val intent = Intent(Intent.ACTION_SEND)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, myImageFileUri)
intent.type = "image/jpg"
startActivity(Intent.createChooser(intent, "Share with"))
loadingDialoglordshiva.dismissDialog()
}
Manifest_file_only_provider_showed
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lordshiva.myapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/fileprovider"
/>
</provider>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lordshiva.myapplication.provider_paths"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
if i run this share intent is opening. but share to WhatsApp,Gmail or something its says file format is not supported . help me I don't know how to solve this.
I am solved by share bitmap image directly to intent.
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.
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.
You should be update filepaths.xml
<paths>
<external-path
name="external_files"
path="." />
</paths>
and Mainifest.xml file
<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/filepaths" />
</provider>
I'm struggling with FileProvider. Even following this Google documentation and this post that is pretty much the same as my problem.
So I'm trying to open a pdf file from external storage. The directory is "Download/nst". I provided the path in file_paths.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="br.com.myapp.bomapp"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"/>
</provider>
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="Download" path="Download/" />
</paths>
This is how I get pdf path:
private File getPdfFile(long workOrderId){
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+"/nst/"+workOrderId);
String[] filesNames = downloads.list(
new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.endsWith(".pdf");
}
}
);
if(filesNames.length > 0){
return new File(downloads, filesNames[0]);
}
return null;
}
And this is how I open pdf:
File pdf = getPdfFile(workOrder.getId());
if(pdf == null){
view.showError(context.getString(R.string.error_no_pdf_found));
return;
}
Intent target = new Intent(Intent.ACTION_VIEW);
Uri fileUri;
if(Build.VERSION.SDK_INT >= 24){
fileUri = FileProvider.getUriForFile(context, "br.com.myapp.bomapp", pdf);
target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else{
fileUri = Uri.fromFile(pdf);
}
target.setDataAndType(fileUri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
view.showError(context.getString(R.string.error_no_pdf_reader_found));
}
Notice I'm using Intent.FLAG_GRANT_READ_URI_PERMISSION.
When debugging the getPdfFile method returns this path for me:
new File(downloads, fileNames[0])": "fileNames[0]=/storage/emulated/0/Download/nst/12345/myName.pdf"
And FileProvider gets me this:
"fileUri = content://br.com.myapp.bomapp/Download/nst/12345/myFile.pdf"
When 12345 is a sub directory which the file is located.
After the file directory is passed to FileProvider it opens the file but screen gets black because file is not there.
But when it is opened with Uril.fromFile the file is shown.
Am I doing something wrong?
I get this error: failed to find configured root that contains /storage/emulated/0/android/data/
There are some similar questions but they are using other location for storing files.
I am using:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) method and this is the code I'm using to open camera:
private void TakePicture() {
photoFile = FileManager.generateFileStampedPhotoFile();
PicturesHelper.TryTakePictureWithAnIntent(this, photoFile, REQUEST_IMAGE_CAPTURE);
}
public static File generateFileStampedPhotoFile()
{
Uri photoFileUri=null;
File photoFile=null;
File outputDir=getPhotoDirectory();
if(outputDir!=null)
{
String timeStamp=new SimpleDateFormat("yyyyMMDD_HHmmss").format(new Date());
String photoFileName="IMG_"+timeStamp+".jpg";
photoFile=new File(outputDir,photoFileName);
// photoFileUri=Uri.fromFile(photoFile);
}
return photoFile;
}
public static void TryTakePictureWithAnIntent(Activity context,File
photoFile,int requestCode)
{
Intent takePictureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(context.getPackageManager())!=null) //if user has camera?
{
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(context,
"com.myapp.fileprovider",
photoFile);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
context.startActivityForResult(takePictureIntent, requestCode);
}
}
}
public static File getPhotoDirectory()
{
File outputDir=null;
String externalStorageState=Environment.getExternalStorageState();
if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
outputDir=new File(new File(pictureDir,"Adriagate"),"Online");
if(!outputDir.exists())//V.P. if directory/ies not exist/s it will be created. mksdrs method follows file structure and creates directory by direcory if needed
{
if(!outputDir.mkdirs())
{
return null;
}
}
}
return outputDir;
}
I have put provider inside AndroidManifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myapp.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
And this is file_paths.xml file:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files name="Whatever_Nothing_Works"/>
You are storing your images in Environment.getExternalStoragePublicDirectory(). That is not one of the supported roots for FileProvider. Plus, your XML has <external-files>, and that is not a supported element for FileProvider (valid ones all end in -path).
Options include:
Changing the location of where you are storing the images to one of the locations supported by FileProvider and adjusting your XML to match
Switching to my StreamProvider and using <external-public-path dir="Pictures">
Changing your XML to <external-path name="whatever" path="Pictures"> and hope for the best
Add this in Menifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Replace in file_paths.xml with
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
Your file is stored under getExternalFilesDir(). That maps to <external-files-path>, not <files-path>