Search code examples
androidkotlinsamsung-galaxy

How to get the name of a file from device storage? (Android Studio)


I am developing an Android app on Android Studio, and one of the features I want to implement is that it can open a txt file containing a JSON and recreate the object specified in the txt file (exported report). There can be multiple files so the user should be able to specify the file from the file picker.

I initially used the approach shown here: https://fvilarino.medium.com/using-activity-result-contracts-in-jetpack-compose-14b179fb87de

Which basically uses Activity Result Contract to get the uri of the file from the file picker. Then I used the get path method from the uri, but this did not work.

On my phone (OnePlus) I saw that the returned uri contained the name of the file. Hence, I specified the path of the folder (the user must place the file in that specific folder), and can select the file and extract the name of the file from the uri (thus getting the complete filepath). However when testing on a Samsung Tab (Galaxy S9 FE) the returned uri is some strange number. Note that both use Android 14, so I have no idea why the results are different.

Function to get the object using uri:

fun getExpRep(uri: Uri): ExportedRep?{
    val path = uri.path?.split("/")
    Log.i("Path last seg" , "${path?.last()}")
    Log.i("Path uri" , "${path}")

    Log.i("Path check", exportsFold.path)
    if (path.isNotNull()){
        if (path!!.isNotEmpty()){
            val filePath = File(exportsFold , path?.last())
            Log.i("path check" , "Filepath: $filePath")
            val content = ByteArray(filePath.length().toInt())
            val stream = FileInputStream(filePath)
            stream.read(content)
            val repJSON = content.decodeToString()
            val expRep = Gson().fromJson(repJSON, ExportedRep::class.java)
            return expRep
        }
        else return  null

    }
    else return null

The uri returned on the OnePlus: content://com.android.externalstorage.documents/document/primary%3ADocuments%2FToeApp%20Exported%20Reports%2FExported_Bruce%20Wayne_27_06_2024.txt

The split uri on OnePlus: [, document, primary:Documents, ToeApp Exported Reports, Exported_Bruce Wayne_27_06_2024.txt]

The uri returned on the Samsung: content://com.android.providers.media.documents/document/document%3A1000000041

Split uri on Samsung: [, document, document%3A1000000041]

The name of the file should be: Exported_(person name)_(date).txt The issue is not with the existence of the folder because the folder is created:

val docFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val exportsFold = File(docFolder, "ToeApp Exported Reports")

fun makeExportsFolder(){
    if (!exportsFold.exists()){
        exportsFold.mkdirs()
    }
    if (!toeAppDir.exists()){
        val makecheck = toeAppDir.mkdirs()
        Log.i("create File", "MakeCheck: $makecheck")
    }                   
}

For testing I was converting the object into a JSON and exporting it to that folder (which the app did correctly), and trying to read the file exported by the app. Since I am able to retrieve the name of file on the OnePlus it works fine. On the Samsung,it is exporting the file to the correct location (same folder), but I am not able to retrieve the file, hence get the following error:

java.io.FileNotFoundException: /storage/emulated/0/Documents/ToeApp Exported Reports/document%3A1000000041: open failed: ENOENT (No such file or directory)

So basically what is a robust way to get at least the name of the selected file across android devices (or at least specifically for the Samsung device). Thank you.


Solution

  • Then I used the get path method from the uri, but this did not work

    That is not supposed to work for anything. Never try using the path from a Uri for anything other than logging purposes.

    Which basically uses Activity Result Contract to get the uri of the file from the file picker

    That article demonstrates the use of ActivityResultContracts.GetContent, which is not limited to files on the filesystem.

    So basically what is a robust way to get at least the name of the selected file across android devices

    There is no requirement that the user select something that is a file.

    You are welcome to attempt to use DocumentFile.fromSingleUri() to create a DocumentFile wrapped around the Uri that you receive from the contract. You can then call getName() to try to get a "display name" for the content identified by the Uri. That should be a user-recognizable name, though it may or may not be a filename. This is much more robust than your "parse a random series of characters in hopes of finding a filename in there". However, not every Uri will work with DocumentFile, and for those that do not, you will have to live without having a reliable display name to use.