在 Nexus 模拟器上使用 android api 23 从画廊获取图像真实路径

Getting image real path from gallary using android api 23 on nexus emulator

这是我打开图库的方式

Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);

这是我的 onActvitityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                Disc.setText(selectedImagePath);
            }
        }
    }

这就是我如何尝试从 gallary 获取真实路径但它什么也没返回,它返回的字符串是空的。

private String getPath(Uri uri) {
        // just some safety built in
        if( uri == null ) {
            Toast.makeText(this, "Error problem with system", Toast.LENGTH_SHORT).show();
            return null;
        }
        String path = "No-Path-Found";
        // try to retrieve the image from the media store first
        // this will only work for images selected from gallery
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if(cursor.moveToFirst()){
            int column_index = cursor
                    .getColumnIndex(MediaStore.Images.Media.DATA);
            path = cursor.getString(column_index);
        }
            cursor.close();
            return path;
    }

任何人都可以帮我解决这个问题,我一直在网上搜索但没有任何效果

A Uri is not a file。没有要求 ACTION_GET_CONTENT return 给你一个来自 MediaStoreUriACTION_GET_CONTENT return 根本不需要 Uri 指向一个文件。

删除您的 getPath() 方法。使用ContentResolveropenInputStream()读入Uri.

标识的内容

发现 android api 19 及以上版本需要使用运行时权限,现在可以完美运行了:)