android - Xamarin android onActivityResult data.extras 返回 null
问题描述
有这个活动允许我拿起或选择一部手机,然后裁剪它并将其设置为 ImageView。然而,图像被裁剪后,它在 Bitmap bitmap = (Bitmap)bundle.GetParcelable("data"); 上返回 null 也试过 Bitmap bitmap = (Bitmap)data.extras.Get("data"); 这是我的代码
private void CameraOpen()
{
CamIntent = new Intent(MediaStore.ActionImageCapture);
file = new File(Android.OS.Environment.ExternalStorageDirectory, "file_" + Guid.NewGuid().ToString() + ".jpg");
uri = Android.Net.Uri.FromFile(file);
CamIntent.PutExtra(MediaStore.ExtraOutput, uri);
CamIntent.PutExtra("return-data", true);
StartActivityForResult(CamIntent, 0);
}
private void GaleryOpen()
{
GalIntent = new Intent(Intent.ActionPick, MediaStore.Images.Media.ExternalContentUri);
StartActivityForResult(Intent.CreateChooser(GalIntent, "Select image from galery"), 2);
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if(requestCode == 0 && resultCode == Result.Ok)
{
CropImage();
}
else if (requestCode == 2)
{
if (data != null)
{
uri = data.Data;
CropImage();
}
}
else if (requestCode == 1)
{
if (data != null)
{
Bundle bundle = data.Extras;
Bitmap bitmap = (Bitmap)bundle.GetParcelable("data");
imgPhoto.SetImageBitmap(bitmap);
}
}
}
private void CropImage()
{
try
{
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.SetDataAndType(uri, "image/*");
CropIntent.PutExtra("crop", "true");
CropIntent.PutExtra("outputX", 180);
CropIntent.PutExtra("outputY", 180);
CropIntent.PutExtra("aspectX", 4);
CropIntent.PutExtra("aspectY", 4);
CropIntent.PutExtra("scaleUpIfNeeded", true);
CropIntent.PutExtra("return-data", "true");
StartActivityForResult(CropIntent, 1);
}
catch (ActivityNotFoundException ex)
{
}
}
出现错误
未处理的异常:
System.NullReferenceException:
非常感谢您的帮助。
解决方案
您正在将 bundle 转换为位图对象,然后在位图对象上使用 GetParcelable() 方法。GetParcelable() 不是位图对象上可用的公共方法,因此您会得到导致空引用的类型不匹配。
https://developer.xamarin.com/api/member/Android.OS.Bundle.GetParcelable/p/System.String/
https://developer.xamarin.com/api/type/Android.Graphics.Bitmap/
推荐阅读
- java - 调整浏览器窗口大小后无法从元素中获取文本(Chrome)
- cmake - 在 CMake 中捕获请求的并行作业
- javascript - 用于制作多个类组件的 React 函数
- powerbi - 添加列时如何重新使用 CALCULATE 函数中使用的过滤器
- r - 通过列表创建循环并将输出添加到数据框
- c - 从二维数组打印一个字符
- tsql - 如何在行号之间添加破折号,在非行号之间添加逗号
- java - Facing Some problem with Firebase InstanceId
- javascript - Redux - Saga,放置父函数
- c# - 片段无法从其他片段中找到变量