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

后端 未结 2 608
清酒与你
清酒与你 2020-11-22 00:56

I am trying to fetch a file this way:

final Intent chooseFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
    String[] mimetypes = {\"application/pdf\"};
         


        
2条回答
  •  日久生厌
    2020-11-22 01:29

    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

提交回复
热议问题