Android: Incorrect File name for selected file(From file chooser)

Viewed 2231

I have a screen where on a button click I open a file chooser and then I select a file named "Test.jpg" for further operation. I use following code to get name of that file.

Uri uri = data.getData();
File file = new File(uri.getPath());
String fileName = file.getName();

Here are the results from debugger

file.getName() => 167522

file.toString() => /external/images/media/167522

I want to get Test.jpg as my filename. Please let me know what is wrong with my code.

3 Answers

This method worked for me in Kotlin:

private fun getFilename(uri: Uri): String? {
    val cursor = activity?.contentResolver?.query(uri, null, null, null, null)
    var filename: String? = null

    cursor?.getColumnIndex(OpenableColumns.DISPLAY_NAME)?.let { nameIndex ->
        cursor.moveToFirst()

        filename = cursor.getString(nameIndex)
        cursor.close()
    }

    return filename
}
Related