onActivityResult’s intent.getPath() doesn’t give me the correct filename

I am trying to fetch a file

Not with that code. That code is asking the user to pick a piece of content. This may or may not be a file.

According to many threads I’m supposed to fetch the file name from the intent with data.getData().getPath()

That was never correct, though it tended to work on older versions of Android.

So what to do?

Well, that depends.

If you wish to only accept files, integrate a file chooser library instead of using ACTION_GET_CONTENT. (UPDATE 2019-04-06: since Android Q is banning most filesystem access, this solution is no longer practical)

If you are willing to allow the user to pick a piece of content using ACTION_GET_CONTENT, please understand that it does not have to be a file and it does not have to have something that resembles a filename. The closest that you will get:

  • If getScheme() of the Uri returns file, your original algorithm will work

  • If getScheme() of the Uri returns content, use DocumentFile.fromSingleUri() to create a DocumentFile, then call getName() on that DocumentFile — this should return a “display name” which should be recognizable to the user

Leave a Comment