DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

ibenge Uforo
ibenge Uforo

Posted on

Display Image with Intent (React-native)

A simple way I came up with to open an image, given a file path linked to the internal storage on mobile (Android)

public void openFileWithIntent(String completeFilePath, String directory) {

                //convert file path to File
        File newFile = new File(String.valueOf(Uri.parse(fileName)));
                // convert create content Uri for sharing with other apps
        Uri contentUri = getUriForFile(reactContext, reactContext.getApplication Context().getPackageName() + ".fileprovider", newFile);

                //create an intent
        Intent intent = new Intent();
                // set the action type 
        intent.setAction(Intent.ACTION_VIEW);
                // set the data and mime type
                String mimeType = ...
        intent.setDataAndType(contentUri, mimeType);
                // Grant temporary access to application opening the file
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // Due to context being outside an activity, we add the flag.
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // Launch file chooser
        reactContext.startActivity(intent);
 }
Enter fullscreen mode Exit fullscreen mode

Add to your android manifest


<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
    <meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Enter fullscreen mode Exit fullscreen mode

We create a file path.xml for above β€œ******android:resource….”******

<?xml version="1.0"encoding="utf-8"?>
<pathsxmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-pathname="photos"path="photos/"  />
</paths>

Enter fullscreen mode Exit fullscreen mode

And that’s it.

Deep dive.

External Links

Top comments (0)

Why You Need to Study Javascript Fundamentals

>> Check out this classic DEV post <<