'Android Open Assets Image File with Intent and FileProvider Shows Size 0

I place all the files in assets folder and use following functions to open them:

fun Fragment.openAssetsFile(fileName: String) {
    val file = getAssetsFile(fileName)
    val fileUri = FileProvider.getUriForFile(requireContext(), "${requireContext().packageName}.provider", file)

    val intent = Intent(Intent.ACTION_VIEW).apply {
        type = "application/${file.extension}"        //<- doesn't work for image (jpg, png)
        data = fileUri

        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    }

    startActivity(intent)
}

fun Fragment.getAssetsFile(fileName: String): File {
    val file = File(requireContext().filesDir, fileName)

    if (!file.exists()) {
        file.outputStream().use { outputStream ->
            requireContext().assets.open(fileName).use { inputStream ->
                inputStream.copyTo(outputStream)
            }
        }
    }

    return file
}

Working perfectly fine with Word, Excel, PPT, PDF, Mp4, Mp3, but for JPG, PNG it shows 0 size like this:

(Had tried setting the mime type image/* but no help.)

enter image description here


Update: Tested on Samsung Tab S5e tablet, Samsung S22 Ultra, Huawei P50 Pro and Samsung Note 9, only the Note 9 has the issue.



Solution 1:[1]

I tried by copying a .png and .jpeg into the assets folder and I can able to access and view both files using the above functions.

I just passed my file name along with extensions like below:

openAssetsFile("fileName.png")

OR

openAssetsFile("fileName.jpeg")

Make sure you have added the file provider in the Android Manifest file:

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

add this provider_paths.xml under res/xml directory

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

Then it should work.

`

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1