从另一个应用程序获取图像时出现 RuntimeException

RuntimeException on getting image from another applications

我已经将我的一个 activity 设置为从另一个应用程序接收图像:

<activity
        android:name=".activities.GetShareImage"
        android:screenOrientation="portrait">
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="image/*" />
        </intent-filter>
    </activity>

并在我的应用程序中使用该图片。但是我有时遇到这个异常:

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{********.activities.GetShareImage}: java.lang.IllegalArgumentException: column '_data' does not exist

我的代码是这样的:

Intent intent = getIntent();
    if (intent != null){

        String action   = intent.getAction();
        String type     = intent.getType();

        if(Intent.ACTION_SEND.equals(action) && type != null){

            if(type.startsWith("image/")){

                Bundle extra = intent.getExtras();
                if(extra.containsKey(Intent.EXTRA_STREAM)){

                    Uri imageUri    = extra.getParcelable(Intent.EXTRA_STREAM);


                    if (imageUri != null){

                        String Scheme   = imageUri.getScheme();

                        if(Scheme.equals("content")){


                            ContentResolver contentResolver = getContentResolver();
                            Cursor cursor = contentResolver.query(imageUri, null, null, null, null);
                            cursor.moveToFirst();

                            String ImagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            if (ImagePath != null) {
                                Uri imageURI = Uri.fromFile(new File(ImagePath));
                                startCropActivity(imageURI);
                            }else {


                                finish();
                            }

                        } else if (Scheme.equals("file")){

                            Uri imgUri  = Uri.parse(extra.getParcelable(Intent.EXTRA_STREAM).toString());
                            startCropActivity(imgUri);
                        }

                    } else {
                        finish();
                    }

                }

            }

        }
    }

我已经检查了 Uri 方案来防止这个问题,但似乎还不够。那么从其他应用程序获取图像的最佳方式是什么? 有没有更好的解决方案?

您的 contentfile 代码都不正确。在 content 的情况下,您假设 MediaStore 知道该图像并具有您可以使用的路径,但两者都不一定正确。在 file 的情况下,您得到 Uri,将其转换为 String,然后将其转换回 Uri,原因不明。

在这两种情况下,extra.getParcelable(Intent.EXTRA_STREAM) Uri。除了将它传递给 startCropActivity() 之外,您无需对此做任何事情。