Search code examples
androidandroid-fileandroid-fileprovider

how to share an video from one app to another using file Provider?


I am trying to share an video from one app to another, but show me an error that "failed to find configure root/data/data/app_name/cache/videos/external files". I can't understand why it's not passing the uri to another app.

can anyone help me to solve this problem

here is file provider path

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="videos/"/>
</paths>
 <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.myapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_provider_paths" />
    </provider>

here is my code

 File video = null;
 shareVideos(video);
 private void shareVideos(File video) {
    Uri uri = getVideoToShare(video);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.setType("videos/mp4");
    context.startActivity(Intent.createChooser(intent, "Share Via"));
}
    private Uri getVideoToShare(File video) {
    File imagefolder = new File(context.getCacheDir(), "videos");
    Uri uri = null;
    try {
        imagefolder.mkdirs();
        File file = new File(imagefolder, "external_files");
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.flush();
        outputStream.close();
        uri = FileProvider.getUriForFile(context, "com.myapp.fileprovider", file);
    } catch (Exception e) {
        Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_LONG).show();
    }
    return uri;
}

Solution

  • File imagefolder = new File(context.getCacheDir(), "videos");
    

    You are storing your file in getCacheDir(). That requires a <cache-path> element in the FileProvider XML metadata resource. That is not what you have. You have:

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

    Change that to:

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