如何在 android 中附加内存文件

how to attach internal memory file in android

我已经动态创建了一个pdf并保存到一个文件夹下的应用程序内存中。 现在我想通过邮件或其他可用的共享选项共享该 pdf。

我正面临

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
                                                                                at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:560)
                                                                                at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:534)
                                                                                at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:376)

下面是我的代码

清单文件

<provider
            android:authorities="mypkgName.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

file_paths.xml: 正在研究 /xml/file_paths

    <?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="media"/>
    <files-path path="app_PDF_Export/" name="Report.pdf" />
    <files-path path="/" name="allfiles" />
</paths>

Java 文件

File newFile = new File(getActivity().getApplicationInfo().dataDir + File.separator +   Constants.folderName, getActivity().getResources().getString(R.string.pdf_name) + ".pdf");
//
  Uri sharedFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getPackageName(), newFile);
            PackageManager packageManager = getActivity().getPackageManager();
            List<ResolveInfo> list = packageManager.queryIntentActivities(emailIntent, PackageManager.MATCH_DEFAULT_ONLY);
            if (list.size() < 1) {
                return;
            }
            String packageName = list.get(0).activityInfo.packageName;

            getActivity(). grantUriPermission(packageName, sharedFileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

            emailIntent.putExtra(Intent.EXTRA_STREAM, sharedFileUri );

谁能告诉我哪里做错了 提前致谢!!!

android:authorities="mypkgName.fileprovider"

不匹配:

FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getPackageName(), newFile);

因此,FileProvder 无法找到 ContentProvider 来读取其 XML 元数据。您需要将正确的权限字符串传递给 getUriForFile().

由于您将 android:authorities 设置为 "mypkgName.fileprovider",请使用:

FileProvider.getUriForFile(getActivity(), "mypkgName.fileprovider", newFile);

getApplicationContext() 在这里毫无意义)