Uri - mayurparmar2/AlarmDemo GitHub Wiki

path covert Content Uri

UriUtil.java

 //"Android/media/com.whatsapp.w4b/WhatsApp Business/Media/.Statuses/"
 //convet into
//"content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia/document/primary%3AAndroid%2Fmedia%2Fcom.whatsapp%2FWhatsApp%2FMedia%2F.Statuses"

  public static Uri getContentUriFromPath(Context context, String path) {
        // Encode path components appropriately
        String encodedPath = path.replace("/", "%2F").replace(" ", "%20");

        // Construct the URI using `DocumentsContract`
        String baseUri = "content://com.android.externalstorage.documents/tree/primary%3A";
        String documentUriSuffix = "document/primary%3A";

        String pathPart = path.startsWith("Android/media/")
                ? encodedPath.substring("Android/media/".length())
                : encodedPath;

        String uriString = baseUri + documentUriSuffix + pathPart;
        Uri contentUri = Uri.parse(uriString);

        Log.d("UriConverter", "Converted URI: " + contentUri.toString());
        return contentUri;
    }

UriUtil

UriUtil.java

public class UriUtil {
    public static String getPath(Context context, Uri uri) {
        Uri uri2 = null;
        if (!DocumentsContract.isDocumentUri(context, uri)) {
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
        } else if (isExternalStorageDocument(uri)) {
            String[] split = DocumentsContract.getDocumentId(uri).split(":");
            if ("primary".equalsIgnoreCase(split[0])) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        } else if (isDownloadsDocument(uri)) {
            String filePath = getFilePath(context, uri);
            if (filePath != null) {
                return Environment.getExternalStorageDirectory().toString() + "/Download/" + filePath;
            }
            String documentId = DocumentsContract.getDocumentId(uri);
            if (documentId.startsWith("raw:")) {
                documentId = documentId.replaceFirst("raw:", "");
                if (new File(documentId).exists()) {
                    return documentId;
                }
            }
            return getDataColumn(context, ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId).longValue()), null, null);
        } else if (isMediaDocument(uri)) {
            String[] split2 = DocumentsContract.getDocumentId(uri).split(":");
            String str = split2[0];
            if ("image".equals(str)) {
                uri2 = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(str)) {
                uri2 = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(str)) {
                uri2 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            return getDataColumn(context, uri2, "_id=?", new String[]{split2[1]});
        }
        return null;
    }

    public static String getFilePath(Context context, Uri uri) {
        Cursor cursor;
        try {
            cursor = context.getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        String string = cursor.getString(cursor.getColumnIndexOrThrow("_display_name"));
                        if (cursor != null) {
                            cursor.close();
                        }
                        return string;
                    }
                } catch (Throwable th) {
                    try {
                        throw th;
                    } catch (Throwable unused) {
                        if (cursor != null) {
                            cursor.close();
                        }
                        return null;
                    }
                }
            }
            if (cursor != null) {
                cursor.close();
            }
            return null;
        } catch (Throwable unused2) {
            cursor = null;
        }
        return null;
    }

    private static String getDataColumn(Context context, Uri uri, String str, String[] strArr) {
        Cursor cursor;
        try {
            cursor = context.getContentResolver().query(uri, new String[]{"_data"}, str, strArr, null);
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        String string = cursor.getString(cursor.getColumnIndexOrThrow("_data"));
                        if (cursor != null) {
                            cursor.close();
                        }
                        return string;
                    }
                } catch (Throwable th) {
                    try {
                        throw th;
                    } catch (Throwable unused) {
                        if (cursor != null) {
                            cursor.close();
                        }
                        return null;
                    }
                }
            }
            if (cursor != null) {
                cursor.close();
            }
            return null;
        } catch (Throwable unused2) {
            cursor = null;
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}

ContentUriToFilePathConverter

test.java
public class ContentUriToFilePathConverter {

    public static String getPathFromContentUri(Context context, Uri contentUri) {
        String filePath = null;

        String[] projection = {OpenableColumns.DISPLAY_NAME};
        ContentResolver contentResolver = context.getContentResolver();

        try (Cursor cursor = contentResolver.query(contentUri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (columnIndex != -1) {
                    String displayName = cursor.getString(columnIndex);
                    File file = new File(context.getExternalFilesDir(null), displayName);
                    filePath = file.getAbsolutePath();
                }
            }
        } catch (Exception e) {
            Log.e("Uri to Path", "Error getting file path from content URI", e);
        }

        return filePath;
    }

    public static void main(String[] args) {
        // Example usage
        Context context = getApplicationContext();
        Uri contentUri = Uri.parse("content://com.demo.example.provider/external_files/MyPC/SampleCSVFile_11kb.csv");
        String filePath = getPathFromContentUri(context, contentUri);
        if (filePath != null) {
            Log.d("FilePath", filePath);
        } else {
            Log.e("FilePath", "Unable to get file path from content URI");
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️