Search code examples
androidandroid-fileprovider

How to get the file path from the recent files in android 10


I'm creating an app in which I have to take the path from the recent files section when I click on the select files button. But in the Android SDK version greater than 23 the uri.getPath() is not giving me the path instead it gives me the id /document/document:100664.

And I want a path like this /document/primary:Download/test.txt.

This uri.getPath() is only working in the Android SDK version less than or equal to 23.

Below is the code which I'm using to get the path.

                if (Build.VERSION.SDK_INT <= 23) {
                    file = mediaFiles.get(0).getPath();
                }
                else {
                    Uri uri= mediaFiles.get(0).getUri();
                    String path = uri.getPath();
                    String path1 = path.substring(path.indexOf(":")+1);
                    File sdcard = Environment.getExternalStorageDirectory();
                    File dir = new File(sdcard.getAbsolutePath()+"/"+path1);
                    file = dir.toString();
                }

So how to get the path from the recent file section in the android SDK versions greater than 23?


Solution

  • String path = uri.getPath();

    File dir = new File(sdcard.getAbsolutePath()+"/"+path1);

    It makes no sense to try to build up a file system path in this way.

    Its the equivalent of all those get real path for uri functions.

    Instead you should open an InputStream for the obtained uri and than read from that stream as if it was a FileInputStream;

    InputStream is = getContentResolver().openInputStream(uri);
    

    Adapt to modern times and use the ur directly.

    Have a look at uri.toString() to see the content scheme you got.