2016-08-24 173 views
1

我使用aFileChooser提供的代码来获取我的应用程序中的共享图像。图库中的图片工作正常,但如果我在Google Chrome中使用图片并尝试分享图片,它会给我一个NPE,因为我的imagePath为空。无法接收共享图像 - Android 6.0

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

uri被认定为MediaStore(和)一般从这个代码:

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

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

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

但是里面getDataColumn()我的光标转储如下:

08-24 12:00:58.196 13186 13256 ReceivePhotos D Cursor is: >>>>> Dumping cursor [email protected] 
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()方法:

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 

电话& OS详细

索尼E5823在Android 6.0.1

+0

为什么要那样做所有的工作? [ContentResolver.openInputStream()](https://developer.android.com/reference/android/content/ContentResolver.html#openInputStream(android.net.Uri))适用于任何URI。 – ianhanniballake

+0

@ianhanniballake你能解释一下怎么做 – stud91

回答

2

你不能和不应尝试曾经得到相应的基本路径一个URI--在绝大多数情况下,你的应用永远不会访问路径本身,但只能通过URI。

值得庆幸的是,你可以直接从URI得到图片的二进制数据:

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.