Android Uri

Android Uri Tutorial and Examples.

A Uri is a mutable URI reference. A URI reference includes a URI and a fragment, the component of the URI following a '#'.

Uri class performs little to no validation. It does this intentially for the sake of performance. Behavior is undefined for invalid input. Uri class is not strict with respect to invalid inputs. It prefers to return garbage rather than throw an exception unless otherwise specified.

Uri API Definition

It is an abstract class deriving directly from the java.lang.Object. Moreover it implements the Parcelable as well as Comparable<Uri> interfaces:

public abstract class Uri 
extends Object implements Parcelable, Comparable<Uri>

Here's it's inheritance hierarchy:


Important Uri Methods

(a). fromFile()

This method will create a Uri from a file. The URI has the form "file://". Encodes path characters with the exception of '/'.

Example: "file:///tmp/android.txt"

Here's it's signature:

public static Uri fromFile (File file)
(b). fromParts

This method will create an opaque Uri from the given components.

public static Uri fromParts (String scheme, 
                String ssp, 
                String fragment)

Quick Android Uri Examples

1. How to get the Extension from a Uri

Let's say you provide us with a Context object as well as a Uri and we wish to get the extension for it and return as a string.

Here's how we do it:

     * To find out the extension of required object in given uri 
    private static String getMimeType(@NonNull Context context, @NonNull Uri uri) {
        String extension;

        //Check uri format to avoid null 
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //If scheme is a content 
            final MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
        } else { 
            //If scheme is a File 
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters. 
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());


        return extension;

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:


What do You Think

Previous Post Next Post