Search code examples
javaandroidurifilepathabsolute-path

Converting a File:///... string to an Absolute URI


So I am making an app that lets users pick images from their gallery to display, as well as take photos from the camera.

The image is previewed via a bitmap that takes the string of the file path. When the user takes a photo the code below handles it (and works):

String path = mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg"
File pictureFile = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
            image1.setImageBitmap(bitmap);

The path is of the format like this:

/storage/emulated/0/Pictures/App/IMG_20150512_130719.jpg

However when I try to select from my library, my code is setup so that the string I am returning formatted like this:

file:////storage/emulated/0/Pictures/App/IMG_20150512_130719.jpg

Now obviously I can (and currently am) split the string and get the path to match the above, but I am curious if there is a standard way to convert between these to?

I saw Uri.parse() but that doesn't work because that returns a URI and I want a String that I can make a file from and then get the absolute path.

If you have a clean suggestion on how I can move from the file://// string to the / string I'm all ears.

Thanks


Solution

  • Converting from file uri to file path:

        String fileUri = "file:///storage/emulated/0/";
        String filePath = Uri.parse(fileUri).getPath();
    

    Converting from file path to file uri:

        String filePath2 = "/storage/emulated/0/";
        String fileUri2 = Uri.fromFile(new File(filePath2)).toString();