从相册菜单选择图片,返回路径为空的解决方法

如下代码从相册菜单选择图片,返回的路径为空

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
其中获取路径的方法如下:
public static String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String filepath = cursor.getString(column_index);
            return filepath;
        } catch (Exception e) {
            return contentUri.getPath();
        } finally {
            if (cursor != null) {
                cursor.close();
            }

        }

 }

 

原因:上面方式从图库获取图片路径是content://media/external/images/media/xxx

而从相册菜单选择图片路径是content://com.android.providers.media.documents/document/xxx

 

解决方法:

方法1:修改打开图库,不打开左侧菜单选择图片(简单、统一、推荐)

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

  方法2:分别获取从图库选择和从左侧菜单选择的路径

posted @ 2017-05-03 23:27  yongfengnice  阅读(736)  评论(0)    收藏  举报