3

I need to get the name and extension of a file that I need to upload. I let the user select the file using an Intent call and get the URI as follows:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
/* stuff */
Uri uri = data.getData();
String filePath = data.getData().getPath();
Log.d("filePath ",filePath);
Log.d("URI ", uri.toString());
String fileName = (new File(filePath)).getName();
Log.d("fileName ",fileName);

but the results are as follows:

com.blah.blah D/URI: content://com.android.providers.downloads.documents/document/354
com.blah.blah D/filePath: /document/354
com.blah.blah D/fileName: 354

the name of the file isn't even 354! its a PDF file (say "Bus e-Ticket.pdf" or "Xender.apk")

String fileName = (new File(filePath)).getAbsolutePath(); also yields the same. how can i get the file name/exstension on disk?

ColonD
  • 954
  • 10
  • 28

2 Answers2

2

but the results are as follows

getPath() is pointless on a Uri with a content scheme. getPath() is pointless on a Uri with any scheme other than file.

the name of the file isn't even 354

There is no requirement that there be a file. https://stackoverflow.com/questions/46060367/android-filename-from-uri-is-not-the-same-as-actual-filename is a Uri, and I feel fairly confident that there is no file on a Stack Overflow server at the path /questions/46060367/android-filename-from-uri-is-not-the-same-as-actual-filename.

how can i get the file name/exstension on disk?

There is no requirement that the user choose something that is a file. You can use DocumentFile.fromSingleUri() and getName() to get a "display name" for the content identified by the Uri. That does not have to be a filename with an extension.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

You can use the MediaStore class to obtain the filename seen by the user. In specific use the MediaColumns interface as shown below

String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
        ContentResolver cr = mctx.getContentResolver();
        Cursor metaCursor = cr.query(uri[0], projection, null, null, null);
        if (metaCursor != null) {
            try {
                if (metaCursor.moveToFirst()) {
                    realFileName = metaCursor.getString(0);
                }
            } finally {
                metaCursor.close();
            }
        }
pcodex
  • 1,812
  • 15
  • 16