Get the value of the data column for this Uri from Context. - Android App

Android examples for App:Context

Description

Get the value of the data column for this Uri from Context.

Demo Code


//package com.java2s;

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

import android.provider.MediaStore;

public class Main {
    /**//from  w ww. j av  a 2 s . com
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri,
            String selection, String[] selectionArgs) {

        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri,
                    new String[] { MediaStore.Images.Media.DATA },
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
}

Related Tutorials