get MediaStore Uri From File - Android Media

Android examples for Media:Media File

Description

get MediaStore Uri From File

Demo Code


//package com.java2s;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;

import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;

public class Main {
    public static Uri getUriFromFile(final String path, Context context) {
        ContentResolver resolver = context.getContentResolver();

        Cursor filecursor = resolver.query(
                MediaStore.Files.getContentUri("external"),
                new String[] { BaseColumns._ID }, MediaColumns.DATA
                        + " = ?", new String[] { path },
                MediaColumns.DATE_ADDED + " desc");
        filecursor.moveToFirst();//from   w  ww.  jav  a  2  s.c o  m

        if (filecursor.isAfterLast()) {
            filecursor.close();
            ContentValues values = new ContentValues();
            values.put(MediaColumns.DATA, path);
            return resolver.insert(
                    MediaStore.Files.getContentUri("external"), values);
        } else {
            int imageId = filecursor.getInt(filecursor
                    .getColumnIndex(BaseColumns._ID));
            Uri uri = MediaStore.Files.getContentUri("external")
                    .buildUpon().appendPath(Integer.toString(imageId))
                    .build();
            filecursor.close();
            return uri;
        }
    }
}

Related Tutorials