How to convert content:// Uri into actual file path? - android

how can I get the actual file path on the SD card where a content:// uri is pointing for an image?

I've adapted the code which #hooked82 linked to:
protected String convertMediaUriToPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}

Content URIs have syntax content://authority/path/id, read here.
Parse id from content URI and query MediaStore.Images.Media.EXTERNAL_CONTENT_URI as follows:
long id = ContentUris.parseId(Uri.parse(contentUri));
Cursor cursor = getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{ MediaStore.Images.Media.DATA },
MediaStore.Images.Media._ID + " = ?", new String[]{ Long.toString(id) },
null);
if (cursor.moveToNext()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();

Related

Cannot remove an image inserted with MediaStore

I'm saving an image loaded with Picasso to be shared afterwards. This is the code I'm using to save it:
String path = MediaStore.Images.Media.insertImage(
mContext.getContentResolver(), mImageBitmap, "Shared image", null);
return Uri.parse(path);
Now, when the image has been shared, I have to delete it using the URI. I've tried some answers I've seen here but none of them has worked. The image still appears in the gallery. These are the methods I have used:
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { new File(mImageUri.toString()).getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst())
{
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
contentResolver.delete(deleteUri, null, null);
}
c.close();
File file = new File(mImageUri.toString());
// This returns false
file.delete();
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(mImageUri.toString()))));
Any idea of what i've done wrong?
Thanks,
Try this for deletion
String[] retCol = { MediaStore.Audio.Media._ID };
Cursor cur = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
retCol,
MediaStore.Images.Media.TITLE + "='"+TEMP_FILE_TITLE+"'", null, null
);
try {
if (cur.getCount() == 0) {
return;
}
cur.moveToFirst();
int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
Uri uri = ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id
);
int cnt = context.getContentResolver().delete(uri, null, null);
}finally {
cur.close();
}
In your case replace TEMP_FILE_TITLE = "Shared image"

Get video info from file path

I have video path. I am able to load video in video using this path.
Now i want some video info from db but my Cursor is always null.
Below is my code.
String videoPath=Uri.fromFile(new File("/storage/emulated/0/Android/data/files/1483767006415.mp4")
final String[] projection = new String[]{MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DURATION};
CursorLoader loader = new CursorLoader(getActivity(), contentUri, projection, null, null, null);
Cursor cursor = loader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
long id = cursor.getLong(cursor.getColumnIndex(projection[0]));
String name = cursor.getString(cursor.getColumnIndex(projection[1]));
String path = cursor.getString(cursor.getColumnIndex(projection[2]));
long duration = cursor.getLong(cursor.getColumnIndex(projection[3]));
cursor.close();
return new ImageObject(id, name, path, false, MEDIA_TYPE_VIDEO, duration);
}
Seems that uri is not proper.
Thanks.
Finally got answer.
Issue was in my URI. Video id was not appended in URI. So i have managed to get video id first and then createdURI. After using this URI, I was able to get all info. Below is code for same.
Uri mainUri;
Cursor cursor1 = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Video.Media._ID},
MediaStore.Video.Media.DATA + "=? ",
new String[]{pathMain}, null);
if (cursor1 != null && cursor1.moveToFirst()) {
int id = cursor1.getInt(cursor1.getColumnIndex(MediaStore.MediaColumns._ID));
cursor1.close();
mainUri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA, pathMain);
mainUri = getContentResolver().insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
}
final String[] projection = new String[]{MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DURATION};
String selection = MediaStore.Video.Media.DATA + "=?";
String selectionArgs[] = {pathMain};
CursorLoader loader = new CursorLoader(getActivity(), mainUri, projection, selection, selectionArgs, null);
Cursor cursor = loader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
long id = cursor.getLong(cursor.getColumnIndex(projection[0]));
String name = cursor.getString(cursor.getColumnIndex(projection[1]));
String path = cursor.getString(cursor.getColumnIndex(projection[2]));
long duration = cursor.getLong(cursor.getColumnIndex(projection[3]));
cursor.close();
return new ImageObject(id, name, path, false, MEDIA_TYPE_VIDEO, duration);
}

Unable to get path for video in Android

I have a URI like so: content://com.android.providers.media.documents/document/video%3A818. I'm trying to get the path so that I can upload to my server with the below method:
private String getRealPathFromURIVideo(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
I also tried the below:
private String getFilePathFromContentUri(Uri selectedVideoUri) {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
I keep getting null from that method! I need the File object after getting the path. Why is that method giving me the null value? Is there something I'm missing here?
I was able to do it like so:
private String getRealPathFromURIForVideo(Uri selectedVideoUri) {
String wholeID = DocumentsContract.getDocumentId(selectedVideoUri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Video.Media.DATA };
String sel = MediaStore.Video.Media._ID + "=?";
Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}

Capture or Take Image from gallery gives null pointer exception in android 5.1?

I want to capture photo and select image from sdcard but when i am selecting image from sdcard it will crash in 5.1 os in other os it is working fine
public String getImagePath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
// Error Coming in this line
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
Try below to fetch path:
public String getImagePath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,
projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
cursor.moveToFirst();
return cursor.getString(column_index);
}

How to get file path from uri?

I am trying to retrieve file path from URI. But my cursor is returning null.
Two problems:
Uri may be audio/ video. So how can I retrieve file path.
Why cursor is returning null?
Here is my code
String[] proj = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
//here cursor is null. So i am getting Null pointer exception
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
Permissions I have used:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
public void songList(){
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cur = contentResolver.query(uri, null, null, null, null);
if(cur.moveToFirst()){
do {
int pathIndex = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
int nameIndex = cur.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
String spath = cur.getString(pathIndex);
String name = cur.getString(nameIndex);
paths.add(spath.substring(4));
songs.add(name);
} while (cur.moveToNext());
}
You can use get File path from diffrent SDk versions
Use RealPathUtils for it
public class RealPathUtils {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
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;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Now get the file Path from URI
String path = null;
if (Build.VERSION.SDK_INT < 11)
path = RealPathUtils.getRealPathFromURI_BelowAPI11(MainActivity.this, uri);
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
path = RealPathUtils.getRealPathFromURI_API11to18(MainActivity.this, uri);
// SDK > 19 (Android 4.4)
else
path = RealPathUtils.getRealPathFromURI_API19(MainActivity.this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
File file = new File(path);

Categories

Resources