I’m developing an Android application that allows users to select files from various sources. I’ve created a function called retrieveFilePath that is supposed to convert URIs into actual file paths. This function works great for files from the gallery and those downloaded, but I am facing an issue when attempting to get the path for files selected from Google Drive.
Here’s a sample Google Drive URI I’m working with: content://com.google.android.apps.docs.storage/document/acc%3D25%3Bdoc%3D12
Can someone guide me on how to address this specific problem? Below is my current code implementation:
public static String retrieveFilePath(final Context context, final Uri uri) {
final boolean isRecentAndroidVersion = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isRecentAndroidVersion && DocumentsContract.isDocumentUri(context, uri)) {
if (isStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] splitDocs = docId.split(":");
final String type = splitDocs[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + splitDocs[1];
}
}
else if (isDownloadDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] splitDocs = docId.split(":");
final String type = splitDocs[0];
Uri mediaContentUri = null;
if ("image".equals(type)) {
mediaContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
mediaContentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { splitDocs[1] };
return getDataColumn(context, mediaContentUri, selection, selectionArgs);
}
else if (isGoogleDriveUri(uri)) {
// Implement logic here for Google Drive file path retrieval
}
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return noPathFound;
}
public static String readInputStream(InputStream inputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 2048);
String line;
StringBuilder result = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}