Skip to content Skip to sidebar Skip to footer

Android - Convert Uri To File Path On Lollipop

I'm currently attempting to make a media player for audio. I'm currently running lollipop. I ran into a problem setting the dataSource for the media player. First, here's how I set

Solution 1:

Lollipop decided to take another course with getting files from the system. (Some say it is from KitKat, but I haven't encountered it yet on KitKat). The code below is to get the filepath on lollipop

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(uri))
    {
        finalString docId = DocumentsContract.getDocumentId(uri);
        finalString[] split = docId.split(":");
        finalString type = split[0];

        Uri contentUri = null;
        if ("audio".equals(type)) 
        {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        finalString selection = "_id=?";
        finalString[] selectionArgs = newString[] {
                split[1]
        };

        String filePath = getDataColumn(context, contentUri, selection, selectionArgs);
    }

isMediaDocument:

publicstaticbooleanisMediaDocument(Uri uri)
{
    return"com.android.providers.media.documents".equals(uri.getAuthority());
}

getDataColumn:

privatestaticString getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs)
{
    Cursor cursor = null;
    finalString column = "_data";
    finalString[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst())
        {
            finalint column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    returnnull;
}

If you still have problems, this is the full answer that checks for images, audio, video, files, etc.

Post a Comment for "Android - Convert Uri To File Path On Lollipop"