Search code examples
androidfileemailemail-attachmentsandroid-fileprovider

Exception Attempt to invoke virtual method


I am trying to setup FileProvider and i'm encountering a lot of problems. The latest is the following exception:

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

My FileProvider looks like this:

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

My path xml file looks like this:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="csv_file" path="files/"/>
</paths>

And the in the MainActivitiy i use this code to pass the file to the intent

File exportDir = new File(getFilesDir(), "");
File file = new File(exportDir, "meritve.csv");
File pot=new File(file.getAbsolutePath());
Uri uri = FileProvider.getUriForFile(MainActivity.this, "com.example.jernej", pot);

Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/csv");
    sendIntent.putExtra(Intent.EXTRA_EMAIL, "mail.example@gmail.com");
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        sendIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(sendIntent, "Send E-mail..."));

I have no idea if I even set up the FileProvider correctly. The file is in the directory /data/data/com.example.jernej.glukozko/files

Please help


Solution

  • I fixed the problem by putting my export file into another subfolder (exportFolder).

    File exportDir = new File(getFilesDir(), "exportFolder"); // here is where i made the first fix
    File file = new File(exportDir, "meritve.csv");
    File pot=new File(file.getAbsolutePath());
    Uri uri = FileProvider.getUriForFile(MainActivity.this,"com.example.jernej.fileprovider", pot); // this is the second fix
    
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/csv");
    sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{ "mail.example@gmail.com"});
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        sendIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(sendIntent, "Send E-mail..."));
    

    So I had to correct my path so now it looks like this:

    <paths xmlns:android="http://schemas.android.com/apk/res/android">
           <files-path name="csv_file" path="exportFolder/"/>
    </paths>