简体   繁体   English

如何在Android中正确获取文件的URI?

[英]How to get URI for file correctly in Android?

I am trying to get the URI for a file like this: 我正在尝试获取像这样的文件的URI:

Uri photoURI = FileProvider.getUriForFile(this,
                        "br.com.[blablabla].sgaconsultor",
                        createImageFile());

private File createImageFile() throws IOException {
        // Create an image file name
        String imageFileName = "registroFoto";

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);

        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                directory
        );
    }

I have a file provider: 我有一个文件提供者:

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="br.com.[blablabla].blabla"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

And the xml is: 而xml是:

<paths>
    <files-path name="br.com.[blablabla].blabla" path="app_imageDir" />
</paths>

But when I run this code I always get this error: 但是,当我运行此代码时,我总是会收到此错误:

java.lang.IllegalArgumentException: Android: FileProvider IllegalArgumentException Failed to find configured root that contains /data/data/**/files/Videos/final.mp4 java.lang.IllegalArgumentException: 安卓:FileProvider IllegalArgumentException无法找到包含/data/data/**/files/Videos/final.mp4的已配置根目录

But no luck so far... So how can I fix this and get the URI for my file? 但是到目前为止还没有运... 那么如何解决这个问题并获取文件的URI?

Any help is really appreciated! 任何帮助都非常感谢!

So how can I fix this and get the URI for my file? 那么,如何解决此问题并获取文件的URI?

Step #1: Get rid of the useless stuff in the Java code. 步骤1:摆脱Java代码中无用的内容。

Step #2: Get the Java code and the file_paths resource to match, as file_paths says that the file path has to be under getFilesDir() and have app_imageDir in it, and your Java code does not have either of those things. 步骤#2:获取匹配的Java代码和file_paths资源,因为file_paths表示文件路径必须位于getFilesDir()并且其中包含app_imageDir ,并且您的Java代码中没有这两个内容。

So, try this: 因此,请尝试以下操作:

private File createImageFile() throws IOException {
    // Create an image file name
    String imageFileName = "registroFoto";
    File directory = new File(getFilesDir(), "app_imageDir");

    directory.mkdirs();

    return File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            directory
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM