如何在android中附加内存文件

时间:2017-02-16 19:43:09

标签: android email attachment internal-storage

我已动态创建了一个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:它位于res / 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 );

任何人都建议我哪里做错了 在此先感谢!!!

1 个答案:

答案 0 :(得分:1)

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()在这里毫无意义)