Unable to receive share image - Android 6.0

2019-02-28 22:08发布

问题:

I am using the code provided by aFileChooser to get able to get the shared image inside my application. Images from the gallery work OK but if i use an image say inside Google Chrome and try to share it, it gives me a NPE as my imagePath is null.

String imagePath = getPath(getActivity(), imageUri);

My uri is identified as MediaStore (and) general from this code:

else if ("content".equalsIgnoreCase(uri.getScheme())) {

        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }

However inside getDataColumn() my cursor dump is as follows:

08-24 12:00:58.196  13186    13256    ReceivePhotos  D  Cursor is: >>>>> Dumping cursor android.content.ContentResolver$CursorWrapperInner@e110803
08-24 12:00:58.196  13186    13256    ReceivePhotos  D  0 {
08-24 12:00:58.196  13186    13256    ReceivePhotos  D  _data=null
08-24 12:00:58.196  13186    13256    ReceivePhotos  D  }
08-24 12:00:58.196  13186    13256    ReceivePhotos  D  <<<<<
08-24 12:00:58.196  13186    13256    ReceivePhotos  D  Cursor column index is: 0

getDataColumn() method:

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
        column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,null);
        Log.d("ReceivePhotos", " Cursor is: " + DatabaseUtils.dumpCursorToString(cursor));

        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            Log.d("ReceivePhotos", " Cursor column index is: " + column_index);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }

    return null;
}

ImageUri log

08-24 12:07:32.780  13629    13696    ReceivePhotos  D  Image uri: content://com.android.chrome.FileProvider/images/screenshot/1472011649310784004280.jpg

Phone & OS Details

Sony E5823 on Android 6.0.1

回答1:

You cannot and should not attempt to ever get the underlying path corresponding with a URI - in the vast majority of cases your app will never have access to the path itself, but only through the URI.

Thankfully, you can get the binary data of the image from the URI directly:

InputStream in;
Bitmap bitmap = null;
try {
  in = getContentResolver().openInputStream(imageUri);
  // You could do anything with the InputStream.
  // Here we'll just get the Bitmap at full size
  bitmap = BitmapFactory.decodeStream(in);
} catch (IOException e) {
  // Something went wrong
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException ignored) {}
  }
}
// Now you have a Bitmap.