Skip to content

Commit

Permalink
Includes an additional method to handle selecting files through a mor…
Browse files Browse the repository at this point in the history
…e robust path resolution, issue Swati4star#1164
  • Loading branch information
u7253836 committed Oct 19, 2024
1 parent c33131e commit a0abf6e
Showing 1 changed file with 34 additions and 23 deletions.
57 changes: 34 additions & 23 deletions app/src/main/java/swati4star/createpdf/util/RealPathUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public String getRealPath(Context context, Uri fileUri) {
}

/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Get a file path from a Uri. This will get the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
Expand All @@ -37,35 +37,46 @@ public String getRealPath(Context context, Uri fileUri) {
*/
private String getRealPathFromURI_API19(final Context context, final Uri uri) {
String path = null;

// DocumentProvider
if (isDriveFile(uri)) {
return null;
}
if (DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];

if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
path = Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
path = Environment.getExternalStorageDirectory() + "/";
}
} else {
path = "storage" + "/" + docId.replace(":", "/");
}

} else if (isRawDownloadsDocument(uri)) {
path = getDownloadsDocumentPath(context, uri, true);
} else if (isDownloadsDocument(uri)) {
path = getDownloadsDocumentPath(context, uri, false);
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];

if ("primary".equalsIgnoreCase(type)) {
path = Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
path = "storage/" + docId.replace(":", "/");
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
path = getMediaDocumentPath(context, uri);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
path = uri.getPath();
}

return path;
}

private String getMediaDocumentPath(Context context, Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(columnIndex);
}
} catch (Exception e) {
e.printStackTrace(); // Consider logging this instead of printing to console
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}

/**
* Get a file path from an Uri that points to the Downloads folder.
*
Expand Down

0 comments on commit a0abf6e

Please sign in to comment.