0

today I'm facing a problem while I try to import an external PDF into my app. This problem occurred only with Android 9 (and maybe 9+). Below the portion of code used to retrieve the file's path:

String[] proj = { MediaStore.Images.Media.DATA, OpenableColumns.DISPLAY_NAME };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);

if (cursor != null && cursor.moveToFirst()) {
    String path = cursor.getString(0); // <-- This is always null

    //In the case it comes from Chrome
    if(pathExternalFile.getAuthority().contains("chrome") || pathExternalFile.getAuthority().contains("fetcher"))
        name = String.format("%s/%s", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), path);
    else
        name = path;

}

Does something change with Android 9? I have read the docs and seems to be all fine.

Lorenzo Vincenzi
  • 1,153
  • 1
  • 9
  • 26
  • There is no requirement for `DATA` to contain anything useful on any version of Android. And, `DATA` is inaccessible on Android Q and higher. There is no requirement for a `Uri` to map to a file on the filesystem that you can access, and it is pretty much guaranteed that it will not be an accessible file on Android Q and higher. For example, you have no access to `Environment.getExternalStoragePublicDirectory()` by default. Use `ContentResolver` and `openInputStream()` to get an `InputStream` on the content identified by the `Uri`. – CommonsWare Aug 08 '19 at 15:06
  • I don't need the content of the file. I'm trying to extract the file's path. How can I retrieve it? – Lorenzo Vincenzi Aug 08 '19 at 15:17
  • You can't. There may not be a file, let alone a meaningful path. For example, `https://stackoverflow.com/questions/57415622/content-resolver-query-on-data-is-null-for-android-9` is a `Uri`. If there is a file for that `Uri`, it is on a server somewhere. More likely, there is no file representing this page, but rather some database entries and some templates. The same holds true for a `content` `Uri`. Whether there is a file or not, and whether there is a meaningful path or not, is an internal implementation detail of the provider. – CommonsWare Aug 08 '19 at 15:23
  • See also https://stackoverflow.com/questions/49221312/android-get-real-path-of-a-txt-file-selected-from-the-file-explorer and https://stackoverflow.com/questions/49226127/how-to-open-local-pdf-file-in-webview-android-studio – CommonsWare Aug 08 '19 at 15:23

0 Answers0