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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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")
}
}
</code>
<code>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") } } </code>
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.

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.

Recognized by Mobile Development Collective

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật