0

Please help or give advice. Faced such a problem. When I open a file from the device (File Manager), I can’t always get a real path to the file being processed.

Open the device manager to select the file to download:

void LoadData(){

    Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
    fileintent.setType("*/*");
    startActivityForResult(fileintent, 1);
}

Get the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data == null){return;}

    Uri uri = data.getData();

    final String filepath = GetPath(uri);

    FileReader file = new FileReader(filepath);
    BufferedReader buffer = new BufferedReader(file);

    ...

}

Method for processing a real path:

public String GetPath(Uri uri) {
    String[] projection = { MediaStore.MediaColumns.DATA };
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return "";
}

This method works on most devices. The resulting Uri and real path in the following format:

content://com.mi.android.globalFileexplorer.myprovider/external_files/Folder/file.csv

/storage/emulated/0/Folder/file.csv

However, on some devices (and in particular on some Samsung) this method does not work. Uri is obtained in this format (and accordingly I can’t get a real path):

content://com.android.externalstorage.documents/document/primary%3AFolder%2Ffile.csv

I can process the resulting delimiters “%3A” and “%2F” with an additional method, but there may be a simpler (elegant) way to get a real path.

Aleksei
  • 79
  • 6
  • "This method works on most devices" -- no, it does not. In addition to the duplicates, see [this bit of documentation](https://developer.android.com/guide/components/intents-common#Storage) and [this bit of documentation](https://developer.android.com/guide/topics/providers/document-provider). – CommonsWare Jan 18 '20 at 18:26
  • You might also be interested in [this documentation](https://developer.android.com/training/data-storage#scoped-storage), [this blog post](https://commonsware.com/blog/2019/06/07/death-external-storage-end-saga.html), and [these blog posts](https://commonsware.com/blog/2019/10/19/scoped-storage-stories-saf-basics.html). – CommonsWare Jan 18 '20 at 18:32

0 Answers0