get MediaStore Image Id - Android Media

Android examples for Media:Picture

Description

get MediaStore Image Id

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;

public class Main {
    private static final String[] ID_COLUMN = { BaseColumns._ID };

    public static int getImageId(final Context aContext, final Uri uri) {

        if (null == uri) {
            return -1;
        }/*from www .  j  a v  a 2 s.  com*/

        Cursor cursor = null;
        try {

            cursor = Images.Media.query(aContext.getContentResolver(),
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    ID_COLUMN, null, null, null);

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

            final int columnIndex = cursor.getColumnIndex(BaseColumns._ID);
            if (-1 == columnIndex) {
                return -1;
            }

            if (!cursor.moveToFirst()) {
                return -1;
            }

            return cursor.getInt(columnIndex);

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

Related Tutorials