Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert file uri to content uri

Tags:

android

i want to choose a file (via file chooser) from astro manager (in my case a *.pdf or *.doc) but the uri contains only the file path ("sdcard/my_folder/test.pdf"). For my application i need the content path like that from image chooser (content://media/external/images/media/2 ). Is there any way to convert a "file:///" to "content://" uri?

Or has anybody an other idea how to solve that problem?

best regards

UPDATE: the main problem is that after i choose my file with filechooser valuecallback.onReceiveValue(uri) method adds a "/" behind the path. So i get an uri like this: "sdcard/my_folder/test.pdf/" and my application thinks pdf is a folder. When i use content uri from image chooser it works.

like image 639
user928473 Avatar asked Sep 05 '11 08:09

user928473


People also ask

What is a content URI?

A content URI is a URI that identifies data in a provider. Content URIs include the symbolic name of the entire provider (its authority) and a name that points to a table (a path). When you call a client method to access a table in a provider, the content URI for the table is one of the arguments.

How get URI from Filepath?

To get File Uri from a absolute path of File you can use DocumentFile. fromFile(new File(path, name)), it's added in Api 22, and returns null for versions below. Show activity on this post. Uri uri = Uri.

What is a URI in Android?

A URI is a uniform resource identifier while a URL is a uniform resource locator.


1 Answers

Like @CommmonsWare said, there is no easy way to convert any type of files into content:// .
But here is how I convert an image File into content://

public static Uri getImageContentUri(Context context, File imageFile) {
    String filePath = imageFile.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 (imageFile.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;
        }
    }
}
like image 153
Ben Lee Avatar answered Oct 06 '22 00:10

Ben Lee