I want to open camera, click and upload the full image to a server. For that, I'm trying to save the image to a location and then upload it from another method. I have been receiving this error in getting the fileprovider to work, and have tried various stack overflow solutions but none seem to work for me.
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.learning.speeeddy.imagereader.app/files/Pictures/IMG_20180627_132113_1596259289.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:738)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:417)
at com.learning.speeeddy.imagereader.feature.MainActivity.dispatchTakePictureIntent(MainActivity.java:67)
at com.learning.speeeddy.imagereader.feature.MainActivity.access$200(MainActivity.java:40)
at com.learning.speeeddy.imagereader.feature.MainActivity$2.onClick(MainActivity.java:323)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22433)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
In MainActivity.java
private void dispatchTakePictureIntent() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(pictureIntent.resolveActivity(getPackageManager()) != null){
//Create a file to store the image
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,"com.learning.speeeddy.imagereader.fileprovider", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(pictureIntent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
}
}
}
private File createImageFile() throws IOException {
String timeStamp =
new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir =
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
In AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.learning.speeeddy.imagereader">
<uses-feature android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" android:required="true"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="aia-compat-api-min-version"
android:value="1" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.learning.speeeddy.imagereader.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
</manifest>
In file_paths.xml (/res/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/com.learning.speeeddy.imagereader.app/files/Pictures" />
</paths>
Related
I'm converting a base64 file to a pdf, so first i'm converting from base64 to an array of bytes and then I write it on a FileOutputStream. My problem is when I try to store it adn then open it with pdf viewer i get this error:
Faild to generate pdf from base64: /storage/emulated/0/Download/conclusions.pdf: open failed: EACCES (Permission denied)
Also I'm giving it the necesarry permissions to work, as I use a File provider because the app works on android 11. Here is the code I use:
Activity:
private fun generatePDFFromBase64(base64: String?, fileName: String?) {
try {
val decodedBytes: ByteArray = Base64.decode(base64, Base64.DEFAULT)
val fos = FileOutputStream(fileName?.let { getFilePath(it) })
fos.write(decodedBytes)
fos.flush()
fos.close()
fileName?.let { openDownloadedPDF(it) }
} catch (e: IOException) {
Log.e("TAG", "Faild to generate pdf from base64: ${e.localizedMessage}")
}
}
private fun openDownloadedPDF(fileName: String) {
val file = File(getFilePath(fileName))
if (file.exists()) {
val path: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
FileProvider.getUriForFile(requireContext(), BuildConfig.APPLICATION_ID + ".provider", file)
} else {
Uri.fromFile(file)
}
generalFile = file
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(path, "application/pdf")
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION
val chooserIntent = Intent.createChooser(intent, "Open with")
try {
startActivity(chooserIntent)
} catch (e: ActivityNotFoundException) {
Log.e("TAG", "Failed to open PDF ${e.localizedMessage}")
}
}
}
private fun getFilePath(filename: String): String {
val file =
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path)
if (!file.exists()) {
file.mkdirs()
}
return file.absolutePath.toString() + "/" + filename + ".pdf"
}
Android 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"
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:name="university"
android:allowBackup="false"
android:icon="${appIcon}"
android:roundIcon="${appIconRound}"
android:label="#string/app_name"
android:supportsRtl="true"
android:hardwareAccelerated="true"
android:theme="#style/Theme.University"
android:usesCleartextTraffic="true">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths"
tools:replace="android:resource" />
</provider>
filepaths:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<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>
open your app info an app permission click all permissions after show all permission click to enable after problem resolved.
var storage_path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
filePathh = Path.Combine(storage_path, filename);
Java.IO.File file = new Java.IO.File(filePathh);
Console.WriteLine("Downloaded file PATH: " + Query.filePathh);
Intent open = new Intent(Intent.ActionView);
open.AddFlags(ActivityFlags.GrantReadUriPermission);
open.SetFlags(ActivityFlags.NewTask);
Context context = Android.App.Application.Context;
Android.Net.Uri fileUri = FileProvider.GetUriForFile(context, "com.companyname.Login.provider", file).NormalizeScheme();
Console.WriteLine("File uri: " + fileUri.Path);
open.SetDataAndType(fileUri, "*/*");
Intent intentC = Intent.CreateChooser(open, "Open With");
intentC.AddFlags(ActivityFlags.GrantReadUriPermission);
intentC.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intentC);
When trying to open a file (when choosing an app to open it - like Docs or HTML reader) we get error File Not Found.
We saw that filePathh and fileUri are different and are not pointing to the same location.
For storage_path:
storage/emulated/0/Download/How_to_initialize_your_Xamarin_app_to_use_AppConnect_C#_APIs.pdf
For Uri path:
/external/Download/How_to_initialize_your_Xamarin_app_to_use_AppConnect_C#_APIs.pdf
Do you want to achieve the result like following GIF?
I put a PDF in Download folder, I use following code to open it.
private void Button1_Click(object sender, System.EventArgs e)
{
var storage_path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
var filePathh = Path.Combine(storage_path, "test.pdf");
Java.IO.File file = new Java.IO.File(filePathh);
Intent open = new Intent(Intent.ActionView);
Uri photoURI = FileProvider.GetUriForFile(this, PackageName + ".provider", file);
open.SetDataAndType(photoURI, "application/pdf");
open.SetFlags(ActivityFlags.NoHistory | ActivityFlags.GrantReadUriPermission);
Intent intent = Intent.CreateChooser(open, "Open File");
try
{
StartActivity(intent);
}
catch (System.Exception)
{
throw;
}
}
Please add provider in your AndroidManifest.xml and read/write persmission.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.app17" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="#style/AppTheme">
<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>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
Create a xml folder in Resource folder and add following provider_paths.xml file
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Here is my demo's link.
https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/App17.zip
Please put PDF in the Download folder like following screenshot.
I need to open documents or images using default app in android phone. so I implemented following codes and it works good but not work only on Android 7 or above. Please let me know what is wrong and how to fix.
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var filePath = Path.Combine(documentsPath, fileName);
var bytes = File.ReadAllBytes(filePath);
//Copy the private file's data to the EXTERNAL PUBLIC location
string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + global::Android.OS.Environment.DirectoryDownloads + "/" + fileName;
File.WriteAllBytes(externalPath, bytes);
Java.IO.File file = new Java.IO.File(externalPath);
file.SetReadable(true);
string application = "";
string extension = Path.GetExtension(filePath);
// get mimeTye
switch (extension.ToLower())
{
case ".txt":
application = "text/plain";
break;
case ".doc":
case ".docx":
application = "application/msword";
break;
case ".pdf":
application = "application/pdf";
break;
case ".xls":
case ".xlsx":
application = "application/vnd.ms-excel";
break;
case ".jpg":
case ".jpeg":
case ".png":
application = "image/jpeg";
break;
default:
application = "*/*";
break;
}
Intent intent = new Intent(Intent.ActionView);
Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
Context context = MainActivity.instance;
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
{
uri = FileProvider.GetUriForFile(context, context.PackageName + ".fileprovider", file);
intent.SetDataAndType(uri, application);
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.NoHistory);
}
else
{
intent.SetDataAndType(uri, application);
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
}
context.StartActivity(intent);
Originally I wasn't corresponding the android version for this functionality but after I read some questions like this, I added it.
Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1" package="com.ibase.mtwpublicapp">
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application android:label="OKS" android:largeHeap="true">
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.oks.mobileapp.fileprovider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/file_paths"></meta-data>
</provider>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id" />
</application>
</manifest>
When I test the app, it shows an exception in this line.
uri = FileProvider.GetUriForFile(context, context.PackageName + ".fileprovider", file);
here is the exception message.
{Java.Lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Download/237309880.doc
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <657aa8fea4454dc898a9e5f379c58734>:0
at Java.Interop.JniEnvironment+StaticMethods.CallStaticObjectMethod (Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <54816278eed9488eb28d3597fecd78f8>:0
at Android.Runtime.JNIEnv.CallStaticObjectMethod (System.IntPtr jclass, System.IntPtr jmethod, Android.Runtime.JValue* parms) [0x00000] in /Users/builder/data/lanes/5749/d8c6e504/source/xamarin-android/src/Mono.Android/Android.Runtime/JNIEnv.g.cs:562
at Android.Support.V4.Content.FileProvider.GetUriForFile (Android.Content.Context context, System.String authority, Java.IO.File file) [0x00077] in <e43264129f744fc09346a273ec4f6c48>:0
at FileManagement.Helpers.FileHelper.OpenFileByName (System.String fileName) [0x0022a] in FileManagement/Helpers/FileHelper.cs:141
--- End of managed Java.Lang.IllegalArgumentException stack trace ---
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Download/237309880.doc
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:712)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:401)
at android.support.v7.app.AlertDialog_IDialogInterfaceOnClickListenerImplementor.n_onClick(Native Method)
at android.support.v7.app.AlertDialog_IDialogInterfaceOnClickListenerImplementor.onClick(AlertDialog_IDialogInterfaceOnClickListenerImplementor.java:30)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
}
Here is the file_paths.xml
<?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-files-path name="my_movies" path="Movies" />
</paths>
I think it may be related to the FileProvider that I declare in manifest.
Thanks for your help!
I got the answer from #CommonsWare after having some discussion.
It needs to add one line to file_path.xml
<external-path name="my_downloads" path="Download" />
here is full xml.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_downloads" path="Download" />
<external-files-path name="my_images" path="Pictures" />
<external-files-path name="my_movies" path="Movies" />
</paths>
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I was trying to make the camera intent work on higher APIs but its crashing when i try to. I think there is something wrong with some paths but i cant figure out what. Its running fine with API 23.
FATAL EXCEPTION: main
Process: ur.mi.android.wgplus05, PID: 22088
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at ur.mi.android.wgplus05.Camera.takePicture(Camera.java:50)
at ur.mi.android.wgplus05.PictureActivity.takePicture(PictureActivity.java:148)
at ur.mi.android.wgplus05.PictureActivity.checkPermission(PictureActivity.java:140)
at ur.mi.android.wgplus05.PictureActivity.onOptionsItemSelected(PictureActivity.java:101)
at android.app.Activity.onMenuItemSelected(Activity.java:3204)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:408)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:113)
at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:679)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Line 50:
Uri photoURI = FileProvider.getUriForFile(activityContext,
BuildConfig.APPLICATION_ID + ".genericfileprovider",
photoFile);
public class Camera {
PictureActivity activityContext;
private String currentPhotoPath;
public Camera(PictureActivity activityContext) {
this.activityContext = activityContext;
}
public void takePicture(int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(activityContext.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
return;
}
// Continue only if the File was successfully created
if (photoFile != null) {
if(Build.VERSION.SDK_INT < 24){
Uri photoURI = Uri.fromFile(photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityContext.startActivityForResult(takePictureIntent, requestCode);
}
else {
Uri photoURI = FileProvider.getUriForFile(activityContext,
BuildConfig.APPLICATION_ID + ".genericfileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityContext.startActivityForResult(takePictureIntent, requestCode);
}
}
}
}
public String getCurrentPhotoPath() {
return currentPhotoPath;
}
public Bitmap getScaledBitmap(String path, Point targetSize) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW / targetSize.x, photoH / targetSize.y);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);
return bitmap;
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_icon_hdx"
android:label="#string/app_name"
android:roundIcon="#drawable/ic_icon_hdx"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Finanzen" />
<activity android:name=".Einkaufsliste" />
<activity android:name=".Einkaufsliste2" />
<activity android:name=".toDoList" />
<activity android:name=".Settings" />
<activity android:name=".PictureActivity" />
<activity
android:name=".Putzplan"
android:windowSoftInputMode="adjustResize" />
<activity android:name=".Kalender" />
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.ur.mi.android.wgplus05.genericfileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
thats 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>
android:authorities="${applicationId}.ur.mi.android.wgplus05.genericfileprovider"
BuildConfig.APPLICATION_ID + ".genericfileprovider"
These do not match. They need to match. Otherwise, FileProvider cannot find the ContentProvider, because you provided an invalid authority name to getUriForFile().
So, for example, you could change the first line to:
android:authorities="${applicationId}.genericfileprovider"
Then, the two values would match (application ID plus .genericfileprovider).
The second argument in getUriForFile should match the authorities attribute from the xml.
BuildConfig.APPLICATION_ID + ".ur.mi.android.wgplus05.genericfileprovider"
i am using this code to run a camera intent to take a photo. All being taken from HERE step by step (full sized camera option)
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) {
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.example.android.fileprovider", 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, ".jpg",storageDir);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Toast.makeText(getActivity(), mCurrentPhotoPath, Toast.LENGTH_SHORT).show();
return image;
}
This is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.terrormachine.swipeapp">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.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=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and my 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/com.example.package.name/files/Pictures" />
</paths>
and i am getting this error:
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.terrormachine.swipeapp/files/Pictures/JPEG_20161015_211933_-593154643.jpg
A little surprising since the file "shell" is there(at this location).
I fount THIS thread but i cant understand a thing...can you explain it humanlike? Any solution is welcome! Its an important project and i need to finish as much as possible and this is a huge stop.
In your files_path.xml, you need to replace com.example.package.name with your apps package name, as explained on developers site.
<?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/com.example.terrormachine.swipeapp/files/Pictures" />
</paths>
Also add camera permission in your AndroidManifest.xml file.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"
android:required="true" />
I think you are missing "uses-feature android:name="android.hardware.camera" android:required="true"" in your manifest.