【问题标题】:java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Pictures/java.lang.IllegalArgumentException:未能找到包含 /storage/emulated/0/Pictures/ 的已配置根目录
【发布时间】:2016-11-08 23:52:09
【问题描述】:

在尝试为我正在尝试开发的应用程序存储使用相机拍摄的照片时遇到错误,寻求帮助。错误是

java.lang.IllegalArgumentException:未能找到包含 /storage/emulated/0/Pictures/JPEG20161108_153704_ 的配置根目录

logcat 在我的代码中指向这个方法,在 FileProvider.getUriForFile 被调用的那一行。

private void dispatchTakePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivity(takePictureIntent); // this worked originally
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, ""+e);
            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(TallyActivity2.this,
                        "com.example.bigdaddy.pipelinepipetally.fileprovider", photoFile);
                takePictureIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

此方法用于创建图像文件

 private File createImageFile() throws IOException {
        /* Create an image file name */
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG" + timeStamp + "_";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile(), imageFileName);
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        /* Tried this also, not working. Leaving for debugging.
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );*/

        File image = new File(path, imageFileName);
        try {
            /* Making sure the Pictures directory exist.*/
            path.mkdir();
            storageDir.createNewFile();
        }catch (Exception e) {
            e.printStackTrace();
        }

        /* Save a file: path for use with ACTION_VIEW intents */
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    }

这里是onActivityResult() 方法,我想用saveImage() 方法将捕获的图像保存到一个类中,并将缩略图设置为ImageView。 saveImage() 方法返回一个字节,因此我可以通过 Intent 将 Bundle 中的字节传递给另一个全屏活动,如果用户单击缩略图ImageView,它将在其中显示。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /* If it's equal to my REQUEST_IMAGE_CAPTURE var, we are all good. */
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            /*Saving to the Pipe class with the saveImage() method below.*/
            sDummyImagePicByte = saveImage(imageBitmap);
            /* Going ahead an setting the thumbnail here for the picture taken*/
            mPipePicImage.setImageBitmap(imageBitmap);
            Log.i(TAG,Arrays.toString(sDummyImagePicByte)+" after assignment from saveImage()");
        }
    }

这是Manifest.xml 文件

<?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="com.example.bigdaddy.pipelinepipetally">

    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <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"
        android:maxSdkVersion="18"/>
    <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"/>
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>

    <application
        android:allowBackup="true"
        android:debuggable="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="HardcodedDebugMode">
        <activity
            android:name=".MainActivity"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".TallyActivity2"
            android:windowSoftInputMode="adjustResize">
        </activity>
        <activity
            android:name=".JobAndDbActivity"
            android:windowSoftInputMode="adjustResize">
        </activity>
        <activity
            android:name=".ExistingTallyActivity"
            android:windowSoftInputMode="adjustResize">
        </activity>
        <activity android:name=".ImageToFullscreen"
            android:windowSoftInputMode="adjustResize">
        </activity>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.bigdaddy.pipelinepipetally.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>

这是我创建并放入 app/res/xml/ 文件夹(我也创建)中的 file_paths.xml 文件。不确定这是否是正确的位置(文件夹)。

<paths >
    <files-path name="my_images" path="files/"/>
    ...
</paths>

这也是onRequestPermissionsResult()

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CAMERA:
                /* if request is canceled, the result arrays are empty */
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    /* Permissions granted so the mPermissionIsGranted boolean is set to true*/
                    mPermissionIsGranted = true;
                } else {
                    /*
                    Permissions denied so the mPermissionIsGranted boolean stays false here and
                    providing a Toast message to the user, letting them know that camera permissions
                    are required for this feature.
                    */
                    Toast.makeText(getApplicationContext(),"Camera permissions required\nfor this" +
                                    "feature.",
                            Toast.LENGTH_LONG).show();
                    /* Continuing to hold the false setting to this boolean since not granted.*/
                    mPermissionIsGranted = false;
                }
                break;
            /* For accessing and writing to the SD card*/
            case MY_PERMISSIONS_REQUEST_SD_CARD:
                /* if request is canceled, the result arrays are empty */
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    /* Permissions granted so the mPermissionIsGranted boolean is set to true*/
                    mPermissionIsGranted = true;
                } else  {
                    /*
                    Permissions denied so the mPermissionIsGranted boolean stays false here and
                    providing a Toast message to the user, letting them know that camera permissions
                    are required for this feature.
                    */
                    Toast.makeText(getApplicationContext(),"SD Card permissions required\nfor this"+
                                    "feature.",
                            Toast.LENGTH_LONG).show();
                    /* Continuing to hold the false setting to this boolean since not granted.*/
                    mPermissionIsGranted = false;
                }
                break;
            /* For the GPS location permissions.*/
            default: MY_PERMISSIONS_REQUEST_FINE_LOCATION:
            /* Still to be implemented .*/
                break;
        }
    }

我非常感谢您对此提供的任何帮助。我还是新手,正在学习 Android。提前致谢。

【问题讨论】:

    标签: java android


    【解决方案1】:

    有点晚了..但我终于解决了。

    根据documentationThe path component only corresponds to the path that is returned by getExternalFilesDir() when called with Environment.DIRECTORY_PICTURES.

    所以用

    getExternalFilesDir(Environment.DIRECTORY_PICTURES)

    而不是

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
    

    你的路径应该是这样的:

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path name="InstructiveRide" path="Android/data/com.package.ride/files/Pictures"/>
    </paths>
    

    如果您在图片目录下有一个子目录,请写下这个。

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path name="InstructiveRide" path="Android/data/com.package.ride/files/Pictures/InstructiveRide/"/>
    </paths>
    

    【讨论】:

    • 为什么这不是公认的答案?这是唯一有效的...
    • 谢谢!您的文档比 Google 的要好....
    【解决方案2】:

    我曾经为文件提供程序的所有路径提供样板代码。您永远不会遇到此类错误。

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
      <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>
    

    更多详情,您可以查看FileProvider - Specifying available Files

    【讨论】:

    • 仍有问题。文件夹路径为/Download/
    • 如何修复文件夹路径为/Download/?
    【解决方案3】:
    <files-path name="my_images" path="files/"/>
    

    这指向getFilesDir() 内的files/ 目录。但是,这不是createImageFile() 想要放置文件的地方。相反,它使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)。您需要:

    1. 确定哪个位置是正确的(或选择其中任何一个以外的其他选项),然后

    2. 同步实现

    【讨论】:

    • 感谢您的回复。那么 XML 文件中的 files-path 指向的是内部文件存储?
    • @J2112O:正确。见the documentation
    • 您好 @CommonsWare ,所以 @J2112O 需要将 &lt;files-path name="my_images" path="files/"/&gt; 更改为 &lt;external-path name="my_images" path="files/"/&gt; 吗? files/ 路径是否正确?还有什么要改变的?
    • @Jaco:切换到getFilesDir() 是最简单的。您可以尝试破解&lt;external-path&gt; 以指向DIRECTORY_PICTURES,但我担心它会不可靠。 &lt;external-path&gt; 文档错误已在几个月前修复。
    • 我也被这个问题卡住了,你解决了吗?我试过getFilesDir() &lt;files-path name="my_images" path="files/"/&gt; 无济于事。
    【解决方案4】:

    我也在尝试升级我的应用程序以避免 FileUriExposedException。我想达到实际问题中提到的相同。我设法与
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

    唯一的诀窍是使用以下路径

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path name="external_files" path="." />
    </paths>
    

    我从以下博客中得到了这个提示。

    https://proandroiddev.com/sharing-files-though-intents-are-you-ready-for-nougat-70f7e9294a0b

    我花了几个小时才弄清楚。我希望它会保护某人的时间。

    【讨论】:

      【解决方案5】:

      我的问题是我在build.gradle文件中为debug模式定义了我的应用程序id的后缀,当我在调试模式下运行应用程序时,包名与我在代码。最好在 xmljava 代码中设置 applicationId(packagename) 变量。

      在您的清单中为您的提供商集执行此操作:

      android:authorities="${applicationId}.fileprovider"
      

      在你的java代码中:

      Uri photoURI = FileProvider.getUriForFile(context,
                          getApplicationContext().getPackageName()+".fileprovider",
      

      并为您的提供程序路径创建两个不同的文件以用于不同的构建变体(发布和调试)

      发布:

      <external-path name="my_images" path="Android/data/com.android.example/files/Pictures" />
      

      用于调试:

      <external-path name="my_images" path="Android/data/com.android.example.debug/files/Pictures" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多