get MediaStore Image File Path - Android Media

Android examples for Media:Picture

Description

get MediaStore Image File Path

Demo Code


//package com.java2s;

import android.content.Context;
import android.database.Cursor;

import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;

public class Main {
    private static final String[] FILE_PATH_COLUMN = { MediaColumns.DATA };

    public static String getImageFilePath(final Context aContext,
            final Uri uri) {

        Cursor cursor = null;/*  w  ww .j av a 2s .c om*/
        try {
            cursor = Images.Media.query(aContext.getContentResolver(), uri,
                    FILE_PATH_COLUMN);

            if (null == cursor) {
                return null;
            }

            final int columnIndex = cursor
                    .getColumnIndex(MediaColumns.DATA);
            if (-1 == columnIndex) {
                return null;
            }

            if (!cursor.moveToFirst()) {
                return null;
            }

            final String path = cursor.getString(columnIndex);
            return path;

        } catch (final NullPointerException e) {
            // This seems to get thrown internally If the image URI is no longer
            // in the DB.
            return null;
        } finally {
            if (null != cursor) {
                cursor.close();
            }
        }
    }

    public static String getImageFilePath(final Context aContext,
            final int aId) {

        final Cursor cursor = aContext.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                FILE_PATH_COLUMN, BaseColumns._ID + " = ? ",
                new String[] { Integer.toString(aId) }, BaseColumns._ID);
        if (null == cursor) {
            return null;
        }

        try {
            final int columnIndex = cursor
                    .getColumnIndex(MediaColumns.DATA);
            if (-1 == columnIndex) {
                return null;
            }

            if (!cursor.moveToFirst()) {
                return null;
            }

            final String path = cursor.getString(columnIndex);
            return path;

        } finally {
            cursor.close();
        }
    }
}

Related Tutorials