Get content uri from file path in android


I know the absolute path of an image (say for eg, /sdcard/cats.jpg). Is there any way to the content uri for this file ?

Actually in my code I download an image and save it at a particular location. In order to set the image in an ImageView currently I open the file using the path, get the bytes and create a bitmap and then set the bitmap in the ImageView. This is a very slow process, instead if I could get the content uri then I could very easily use the method ImageView.setImageUri(uri)

2/12/2013 5:18:05 PM

Accepted Answer

Try with:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));

Or with:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
1/7/2015 8:20:41 AM


Here it is assumed that your media (Image/Video) is already added to content media provider. If not then you will not able to get the content URL as exact what you want. Instead there will be file Uri.

I had same question for my file explorer activity. You should know that the contenturi for file only supports mediastore data like image, audio and video. I am giving you the code for getting image content uri from selecting an image from sdcard. Try this code, maybe it will work for you...

public static Uri getImageContentUri(Context context, File imageFile) {
  String filePath = imageFile.getAbsolutePath();
  Cursor cursor = context.getContentResolver().query(
      new String[] { MediaStore.Images.Media._ID },
      MediaStore.Images.Media.DATA + "=? ",
      new String[] { filePath }, null);
  if (cursor != null && cursor.moveToFirst()) {
    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
    return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
  } else {
    if (imageFile.exists()) {
      ContentValues values = new ContentValues();
      values.put(MediaStore.Images.Media.DATA, filePath);
      return context.getContentResolver().insert(
          MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } else {
      return null;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow