Convert uri file to uri content

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

Or does anyone have another idea how to solve this problem?

Regards

UPDATE: the main problem is that after I select my file using the filechooser valuecallback.onReceiveValue (uri) method, a "/" is added along the path. So I get a uri like this: "sdcard / my_folder / test.pdf /" and my application considers pdf to be a folder. When I use uri content from image chooser, it works.

+10
source share
5 answers

Like @CommmonsWare, there is no easy way to convert any type of file to content: //.
But here is how I convert the image to a file: //

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;
        }
    }
}
+15
source

Here's a simpler review method that may come in handy.

google Android:

/**
 * Converts a file to a content uri, by inserting it into the media store.
 * Requires this permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 */
protected static Uri convertFileToContentUri(Context context, File file) throws Exception {

    //Uri localImageUri = Uri.fromFile(localImageFile); // Not suitable as it not a content Uri

    ContentResolver cr = context.getContentResolver();
    String imagePath = file.getAbsolutePath();
    String imageName = null;
    String imageDescription = null;
    String uriString = MediaStore.Images.Media.insertImage(cr, imagePath, imageName, imageDescription);
    return Uri.parse(uriString);
}
+6

, Share Folder:

  1. xml

  2. file_paths.xml :

<files-path name="internal" path="/"/>
  1. , :
<provider android:name="android.support.v4.content.FileProvider"
               android:authorities="com.dasmic.filebrowser.FileProvider"
               android:windowSoftInputMode="stateHidden|adjustResize"
               android:exported="false"
               android:grantUriPermissions="true">
               <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/file_paths" />
</provider>

4. "content://" :

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //Required for Android 8+
Uri data = FileProvider.getUriForFile(this, "com.dasmic.filebrowser.FileProvider", file);
intent.setDataAndType(data, type);
startActivity(intent);
+2

MediaScannerConnection

File file = new File("pathname");
MediaScannerConnection.scanFile(getContext(), new String[]{file.getAbsolutePath()}, null /*mimeTypes*/, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String s, Uri uri) {
                // uri is in format content://...
            }
        });
+1

FileProvider

step 1: create java- file and extendsits withFileProvider

public class MyFileProvider extends FileProvider {

}

step 2: create a resource file xmldirectory res/xml/and copy this code into it

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

step 3: in your file manifestunder <Application>add this code

<provider
            android:name="MyFileProvider" <!-- java file created above -->
            android:authorities="${applicationId}.MyFileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/> <!-- xml file created above -->
        </provider>

Step 4: use this code to get Urito the content://format

Uri uri = FileProvider.getUriForFile(CameraActivity.this, "your.package.name.MyFileProvider", file /* file whose Uri is required */);

Note: you may need to add read permission

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
0
source

All Articles