Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting path from Uri from Google Photos app

Tags:

android

uri

I have an app which allows to select photos with an external app. Then I take the path of the photo from the uri and use it for internal actions.

When user selects a photo with Google Photo, if the picture is locally stored then the next code works perfectly. But if the picture is in the cloud the result of cursor.getString(index) is null.

I've search for some info, but not sure about the solution

final String[] projection = { "_data" };
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow("_data");
    return cursor.getString(index);
}

Thank you!

like image 411
adalpari Avatar asked Apr 19 '17 15:04

adalpari


1 Answers

Finally and according to @CommonsWare answer and the previous post about this issue I solved getting the InputStream from the uri, coping into a new temporal file and passing the path to the function I need to use.

Here is the simplified code:

public String getImagePathFromInputStreamUri(Uri uri) {
    InputStream inputStream = null;
    String filePath = null;

    if (uri.getAuthority() != null) {
        try {
            inputStream = getContentResolver().openInputStream(uri); // context needed
            File photoFile = createTemporalFileFrom(inputStream);

            filePath = photoFile.getPath();

        } catch (FileNotFoundException e) {
            // log
        } catch (IOException e) {
            // log
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return filePath;
}

private File createTemporalFileFrom(InputStream inputStream) throws IOException {
    File targetFile = null;

    if (inputStream != null) {
        int read;
        byte[] buffer = new byte[8 * 1024];

        targetFile = createTemporalFile();
        OutputStream outputStream = new FileOutputStream(targetFile);

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }
        outputStream.flush();

        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return targetFile;
}

private File createTemporalFile() {
    return new File(getExternalCacheDir(), "tempFile.jpg"); // context needed
}
like image 167
adalpari Avatar answered Oct 06 '22 00:10

adalpari