bubu uwu
bubu uwu

Reputation: 483

android : file Uri to Content Uri. (converting)

I have two type of Uris.

type one :

content://media/external/images/media/465

content://media/external/images/media/466

type two :

file:///storage/emulated/0/DCIM/Camera/20151112_185009.jpg

file:///storage/emulated/0/testFolder/20151112_185010.jpg

What is difference and how to convert file uri to content uri?

Because, file uri is just causing error. When I call method :

ContentResolver contentResolver = getContentResolver();
fis = (FileInputStream) contentResolver.openInputStream(fileTypeUri);

how do I fix this?

Upvotes: 0

Views: 5414

Answers (2)

Vivek Hirpara
Vivek Hirpara

Reputation: 807

Try It :)

public static Uri getImageContentUri(Context context, File file) {
        String filePath = file.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (file.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

Upvotes: 1

etherton
etherton

Reputation: 942

If you're trying to share data that is stored as part of your app with another app you'll need to use a content:// scheme and not a file:// scheme. This can be accomplished using the FileProvider class found here: https://developer.android.com/reference/android/support/v4/content/FileProvider.html.

By using the FileProvider class you can more precisely and more securely define what files your app can share.

Though be aware that external-cache-path and external-files-path don't work despite what the documentation says. See: how to set FileProvider for file in External Cache dir for more info.

Upvotes: 0

Related Questions