Search code examples
androidurifilepathsharing

How to receive and save image shared from another application


if(intent.getType().startsWith("image/")){
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    imageView.setImageUri(imageUri);
}

Need to save this image in my applications data directory. Querying on content resolver returns path to only those image files which are already saved in the device. like,

private String getPathFromURI(Uri contentURI) {
        String result = null;
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(contentURI, null, null, null, null);
            cursor.moveToFirst();
            int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return result;
    }

but this does not works all the times because some of those image files are in private directories of the apps. What to do to get read access to such files, so that copies of shared files can be written/saved for my application? is there something wrong, that I should do some other way? kindly help, thank you.


Solution

  • Queering on content resolver returns path to only those image files which are already saved in the device

    It is far worse than that. This only works for a Uri from the MediaStore, and even then only in certain situations.

    What to do to get read access to such files, so that i can write copies of them for my application?

    Step #1: Use getContentResolver().openInputStream() to get an InputStream on the content represented by the Uri

    Step #2: Create a FileOutputStream for your desired copy

    Step #3: Copy the bytes from the InputStream to the FileOutputStream using standard Java file I/O

    IOW, this is not significantly different than using HttpURLConnection to download a file from a URL.