retrieve absolute path when select image from gallery kitkat android

Here is one way to access the Absolute path after selecting file.

After getting data in new URI format for KK(KitKat) like this way

content://com.android.providers.media.documents/document/image:2505

Just extract ID of your document

if(requestCode == GALLERY_KITKAT_INTENT_CALLED && resultCode == RESULT_OK){

    Uri originalUri = data.getData();

    final int takeFlags = data.getFlags()
                        & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    // Check for the freshest data.
    getContentResolver().takePersistableUriPermission(originalUri, takeFlags);

    /* now extract ID from Uri path using getLastPathSegment() and then split with ":"
    then call get Uri to for Internal storage or External storage for media I have used getUri()
    */

    String id = originalUri.getLastPathSegment().split(":")[1]; 
    final String[] imageColumns = {MediaStore.Images.Media.DATA };
    final String imageOrderBy = null;

    Uri uri = getUri();
    String selectedImagePath = "path";

    Cursor imageCursor = managedQuery(uri, imageColumns,
          MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);

    if (imageCursor.moveToFirst()) {
        selectedImagePath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
    }
    Log.e("path",selectedImagePath ); // use selectedImagePath 
}else if() {
      // for older version use existing code here
}

// By using this method get the Uri of Internal/External Storage for Media
private Uri getUri() {
    String state = Environment.getExternalStorageState();
    if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
        return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

    return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}

Leave a Comment