Retrieve Absolute Path When Select Image From Gallery Kitkat Android
As I am supporting my app to Kitkat version, now in this the way of retrieve file from gallery was different. I have preferred this Android Gallery on KitKat returns different Uri
Solution 1:
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){
UrioriginalUri= data.getData();
finalinttakeFlags= 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()
*/Stringid= originalUri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
finalStringimageOrderBy=null;
Uriuri= getUri();
StringselectedImagePath="path";
CursorimageCursor= 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
}elseif() {
// for older version use existing code here
}
// By using this method get the Uri of Internal/External Storage for Mediaprivate Uri getUri() {
Stringstate= Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
Solution 2:
Pratik's solution helped me alot. Following is the version which works for me in Kitkat 4.4.2. Three things which i changed are 1) Using content resolver to get the path 2) originalUri.getLastPathSegment().split(":")[1] gives me index out of bound so i'm using index 0 instead.Its been working so far 3) Removed takeflags and check for freshest data as we are filtering the cursor with id.
try {
UrioriginalUri= data.getData();
String pathsegment[] = originalUri.getLastPathSegment().split(":");
Stringid= pathsegment[0];
final String[] imageColumns = { MediaStore.Images.Media.DATA };
finalStringimageOrderBy=null;
Uriuri= getUri();
CursorimageCursor= activity.getContentResolver().query(uri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, null);
if (imageCursor.moveToFirst()) {
value = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
} catch (Exception e) {
Toast.makeText(activity, "Failed to get image", Toast.LENGTH_LONG).show();
}
Solution 3:
Perfectly working solution:
package utils;
/**
* Created by layer on 4/21/2015.
*/import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
publicclassImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/@TargetApi(Build.VERSION_CODES.KITKAT)publicstatic String getPath(final Context context, final Uri uri) {
// check here to KITKAT or new versionfinalbooleanisKitKat= Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProviderif (isExternalStorageDocument(uri)) {
finalStringdocId= DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
finalStringtype= split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
// DownloadsProviderelseif (isDownloadsDocument(uri)) {
finalStringid= DocumentsContract.getDocumentId(uri);
finalUricontentUri= ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProviderelseif (isMediaDocument(uri)) {
finalStringdocId= DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
finalStringtype= split[0];
UricontentUri=null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} elseif ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} elseif ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
finalStringselection="_id=?";
final String[] selectionArgs = newString[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)elseif ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote addressif (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// Fileelseif ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
returnnull;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/publicstatic String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursorcursor=null;
finalStringcolumn="_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
finalintindex= cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
returnnull;
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/publicstaticbooleanisExternalStorageDocument(Uri uri) {
return"com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/publicstaticbooleanisDownloadsDocument(Uri uri) {
return"com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/publicstaticbooleanisMediaDocument(Uri uri) {
return"com.android.providers.media.documents".equals(uri
.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/publicstaticbooleanisGooglePhotosUri(Uri uri) {
return"com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
}
https://github.com/layerlre/Android-Utility-Class/blob/master/utils/ImageFilePath.java
Hope works for you.
Solution 4:
Bitmapbitmap= MediaStore.Images.Media
.getBitmap(getActivity().getContentResolver(), uri);
I hope that this will help you.
Post a Comment for "Retrieve Absolute Path When Select Image From Gallery Kitkat Android"