1

I am trying to retrieve the Uri of a file. The file is stored inside:

/storage/emulated/0/AppName/FileName.png

If I used Uri.fromFile(file), what I got was

file:///storage/emulated/0/AppName/FileName.jpg

What I wanted is something of this format:

content://media/external/images/media/51128? 

Why doesn't Uri.fromFile(file) gives me this? And how can I get this?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
yeeen
  • 4,911
  • 11
  • 52
  • 73
  • 1
    "Why doesn't Uri.fromFile(file) gives me this?" -- because what you want, for some reason, is a `Uri` from the `MediaStore` `ContentProvider`. "And how can I get this?" -- query the `MediaStore` `ContentProvider`. Whether or not you will find your specific file in there is another matter. – CommonsWare Nov 01 '15 at 10:46

1 Answers1

1

Uri.fromFile() gives a file URI, not a content URI, which is what you want.

As to how you can get this, I'd suggest you see this answer since it covers conversion both from and to content URI.

The relevant code, modified slightly to match your media type (image):

/**
 * Gets the MediaStore video ID of a given file on external storage
 * @param filePath The path (on external storage) of the file to resolve the ID of
 * @param contentResolver The content resolver to use to perform the query.
 * @return the video ID as a long
 */
private long getImageIdFromFilePath(String filePath,
    ContentResolver contentResolver) {


    long imageId;
    Log.d(TAG,"Loading file " + filePath);

            // This returns us content://media/external/images/media (or something like that)
            // I pass in "external" because that's the MediaStore's name for the external
            // storage on my device (the other possibility is "internal")

    Uri imagesUri = MediaStore.Images.getContentUri("external");

    Log.d(TAG,"imagesUri = " + imagessUri.toString());

    String[] projection = {MediaStore.Images.ImageColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = contentResolver.query(imagesUri, projection, MediaStore.Images.ImageColumns.DATA + " LIKE ?", new String[] { filePath }, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(projection[0]);
    imageId = cursor.getLong(columnIndex);

    Log.d(TAG,"Image ID is " + imageId);
    cursor.close();
    return imageId;
}
Community
  • 1
  • 1
Steven Hewitt
  • 302
  • 3
  • 12
  • When do u need a file URI and when do u need a content URI? Why is there two types of URI? – yeeen Nov 01 '15 at 11:03