0

I want to get image URI from another app like a gallery, google drive, whats app etc

I have registered following intent filter :

        <intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:mimeType="image/*" />
        </intent-filter>

and to get the actual path

    if (_uri != null && "content".equals(_uri.getScheme())) {
                Cursor cursor = this.getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                cursor.moveToFirst();
                filePath = cursor.getString(0);
                cursor.close();
            } else {
                filePath = _uri.getPath();
            }

with this, I am able to see my app from gallery whats app. From gallery, I am able to get image path URI but when I am trying to share from other apps like whatsapp or google drive its give me null how to get path from different types of app

Surbhi Aggarwal
  • 777
  • 8
  • 25
droid
  • 83
  • 1
  • 1
  • 8
  • Your question is not clear. Do you want to select any image from other apps or do you want to share the image of ur app to other apps? – Surbhi Aggarwal Sep 16 '19 at 06:29
  • i will be sharing an image from other app and my app will be receiving image for example from google drive u can share it on whats app – droid Sep 16 '19 at 06:38

2 Answers2

0

Check Out this may help

In the manifest :

  <activity android:name=".ui.MyActivity" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND_MULTIPLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

And on Activity

void onCreate (Bundle savedInstanceState) {
    ...
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleSendText(intent); // Handle text being sent
        } else if (type.startsWith("image/")) {
            handleSendImage(intent); // Handle single image being sent
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleSendMultipleImages(intent); // Handle multiple images being sent
        }
    } else {
        // Handle other intents, such as being started from the home screen
    }
    ...
}

For more info check : https://developer.android.com/training/sharing/receive#java

Wisdomrider
  • 170
  • 7
  • its give content uri not actual uri . it works from gallery but not from google drive or other app – droid Sep 16 '19 at 06:39
0

After getting the contentURI, you can use the following method to get the actual Uri using following method.

// You can use call the method from your activity like this.
String path = getPath(this,contentURI);

//This the method to get the actual path from the uri
public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
if (isGoogleDriveUri(uri)) {
                return getDriveFilePath(uri, context);
}
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return uri.getPath();
    }

    /**
     * Method to check if the uri is external storage document
     *
     * @param uri uri
     * @return true if the uri authority is of external storage
     */
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * Method to download the document
     *
     * @param uri uri
     * @return true if uri is of type download documents
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri.
     */
    private static String getDataColumn(Context context, Uri uri, String selection,
                                        String[] selectionArgs) {
        final String column = "_data";
        final String[] projection = {
                column
        };
        try (Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null)) {
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        }
        return null;
    }

// isGoogleDriveUri method 

  private static boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }

//getDriveFilePath method 
 private static String getDriveFilePath(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
        return file.getPath();
    }

//For whatsapp u can use: // whatsapp returns the uri in this particular way - content://com.whatsapp.provider.media/item/xxxxx

InputStream is = getContentResolver().openInputStream(uri);

Now u have to get the file path using this input stream. Then u have to read from input stream.

U may have to add it in the last if else block like:-

if ("content".equalsIgnoreCase(uri.getScheme())) {
            String path = "";
            try{
                path = getDataColumn(context, uri, null, null);
            }catch (Exception e){
                try {
                    InputStream is = context.getContentResolver().openInputStream(uri);
                    //TODO: read this input stream to get data
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            return path;
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            String path = "";
            try{
                path = uri.getPath();
            }catch (Exception e){
                try {
                    InputStream is = context.getContentResolver().openInputStream(uri);
                    //TODO: read this input stream to get data
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            return path;
        }
Surbhi Aggarwal
  • 777
  • 8
  • 25
  • what abt whats app and other apps like telegram – droid Sep 16 '19 at 07:08
  • its giving null for other apps – droid Sep 16 '19 at 07:12
  • U have to check whether these applications expose the path or not, if they expose the path then u have to check for every type of Content Uris like used in public_downloads, otherwise if they return inputstream then u have to get the file by inputstream. – Surbhi Aggarwal Sep 16 '19 at 07:15
  • I have updated my answer for whatsapp but u have to check whether the application expose path or not. If the application exposes path u can get it specifying the content uri if it exposes input stream then u have to read input stream to get data – Surbhi Aggarwal Sep 16 '19 at 07:27
  • same logic for other apps like telegram ,dropbox ? – droid Sep 16 '19 at 07:33
  • Yes, for the applications where the images are not downloaded, u can use the same logic as used in google drive but u have to check uri.... As checked in google drive same will be applicable for dropbox. For other applications, like the chat applications, viber, whatsapp, line, u have to check whether they path or not. If they exposes path they u can get the actual path from uri but if they dont expose path u have to read the data from input stream – Surbhi Aggarwal Sep 16 '19 at 07:36
  • @droid Please accept and upvote my answer, if it helped. – Surbhi Aggarwal Sep 16 '19 at 07:48
  • how to get uri from that . can we add getContentResolver().openInputStream(uri); to gallery ? – droid Sep 16 '19 at 09:18
  • No, we cannot apply this to gallery, you have to use getPath method for every case of yours using if else as specified if no block is executed then add a final else part where u can use openInputStream. Every selection of urs will return contenturi but u have to check the different cases on that content uri for getting actual path – Surbhi Aggarwal Sep 16 '19 at 09:24
  • have added in ur snippet ? – droid Sep 16 '19 at 09:29
  • I have not added it in the if else loop, but i have mentioned it separately, i guess u can do that. – Surbhi Aggarwal Sep 16 '19 at 09:36
  • Caused by: java.lang.IllegalArgumentException: column '_data' does not exist. Available columns: [] – droid Sep 16 '19 at 10:03
  • u have to debug to check why u r getting this problem, as far as I understand if u have added an else block in the end then the content.equalsIgnoreCase block is running before that. – Surbhi Aggarwal Sep 16 '19 at 10:10