繁体   English   中英

当我从库中选择一个图像时,onActivityResult中的Intent数据为null

[英]Intent data is null in onActivityResult when I pick an Image from gallery

我需要从库中获取一个图像,并将其转换为位图。

这是发送Intent的代码:

Intent i = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);

onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mResultLoadImage && resultCode == RESULT_OK && data != null) {
            Uri pickedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(pickedImage, filePath,
                    null, null, null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor
                    .getColumnIndex(filePath[0]));
            bitmap = BitmapFactory.decodeFile(imagePath);
            someFunction(bitmap);
            cursor.close();
        }
}

我总是得到一个NullPointerException,并且使用debuger,我发现数据Intent为null。 有解决方案吗

试试这个,它应该工作:

Intent intent = new Intent(Intent.ACTION_PICK);
startActivityForResult(intent, RESULT_LOAD_IMAGE);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE) {
        Uri imageUri = data.getData();
        Bitmap imgBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, null);
        // then do whatever you want with the bitmap
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM