Skip to content

Instantly share code, notes, and snippets.

@jdeloach
Created July 24, 2012 21:22
Show Gist options
  • Save jdeloach/3172742 to your computer and use it in GitHub Desktop.
Save jdeloach/3172742 to your computer and use it in GitHub Desktop.
File Path to Android Content URI, credit to http://stackoverflow.com/a/11603841/1079757. Some modifications to use as an image and more polished this way. Took forever to find. Useful for working with the Android Gallery App
/**
* Returns the Uri which can be used to delete/work with images in the photo gallery.
* @param filePath Path to IMAGE on SD card
* @return Uri in the format of... content://media/external/images/media/[NUMBER]
*/
private Uri getUriFromPath(String filePath) {
long photoId;
Uri photoUri = MediaStore.Images.Media.getContentUri("external");
String[] projection = {MediaStore.Images.ImageColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = getContentResolver().query(photoUri, projection, MediaStore.Images.ImageColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
photoId = cursor.getLong(columnIndex);
cursor.close();
return Uri.parse(photoUri.toString() + "/" + photoId);
}
@xmenxwk
Copy link

xmenxwk commented Sep 6, 2013

doesnt work :( cursor always empty. Tested on Desire S, ICS 4.0.3

@ebuildy
Copy link

ebuildy commented May 22, 2014

Same thing, not working ;-(

@octopuslaowang
Copy link

NPE because you don't add the path to system db.
How to add? Follow the under code...

        // insert system media db
        String path = yourPath;
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE,
                FilenameUtils.getBaseName(path));
        values.put(MediaStore.Images.Media.DESCRIPTION,
                "Image capture by camera");
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put("_data", path);
        getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

@ShreyashPromact
Copy link

@octopuslaowang

How to get content uri after adding that to MediaContent (System db) ?

Sincerely,
Shreyash

@HarishSivachalam
Copy link

Cursor Throws CursorIndexOutOfBoundsException

@Dharmarajm
Copy link

how to get the file path to content uri in ionic 3?

@camrongiuliani
Copy link

Try this. Tested Android P, PH-1

File f = new File(resource1.getResource());
                    
Uri contentUri = Uri.fromFile(f);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment