Reputation: 79
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.
Upvotes: 0
Views: 520