What I'm trying to do in my application is to let the user choose a picture. As recommended in the most blogs, I delegate this functionality to the apps installed on devices. I throw a intent with these properties:
Intent pickPhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickPhotoIntent.setType("image/*");
pickPhotoIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
pickPhotoIntent.addCategory(Intent.CATEGORY_OPENABLE);
with mentioned intent user can pick photo from these application in Sony Xperia XZ with Oreo Android version:
the Uri which receive in onActivityResult()
,
1) if user pick photo from Google Drive is like "content://com.google.android.apps.docs.storage.legacy/enc%3DVmocHGi0P0XS_iMZxaRt3ofmo%0A"
2) if user pick photo from Download is like "content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FBabies%2FCR.gif"
3) if user pick photo from other apps is like "content://media/external/images/media/132411"
I want to know how I can extract the path of selected picture and get content from first and second Uri.
I use this method for other Uri (third Uri) and it works.
public static String getRealPathFromURI(Context context, Uri uri) {
String filePath = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
return cursor.getString(columnIndex);
}
cursor.close();
}
return null;
}
}