我正在使用 aFileChooser 即可在我的应用程序中获取共享图像。画廊中的图像可以正常工作,但是如果我在Google Chrome中使用图像说并尝试共享它,那么我的 imagePath 为null会给我NPE。
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);我的 uri 被标识为MediaStore(并且),通常从以下代码中获取:
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); }但是在 getDataColumn()我的光标转储如下:
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: 0getDataColumn()方法:
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日志
08-24 12:07:32.780 13629 13696 ReceivePhotos D Image uri: content://com.android.chrome.FileProvider/images/screenshot/1472011649310784004280.jpg电话&操作系统详细信息
Android 6.0.1上的Sony E5823
Sony E5823 on Android 6.0.1
推荐答案您不能也不应该尝试获取与URI相对应的基础路径-在大多数情况下,您的应用将永远无法访问该路径本身,而只能通过URI。
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.
值得庆幸的是,您可以直接从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.更多推荐
无法接收共享图像
发布评论