我有一个机制,我仍在努力,我正在尝试消化代码,我从各种来源得到了我的东西。基本上有一个ImageView,您可以在其中设置您的个人资料图片,您可以使用相机拍照或从图库中选择一张图片。我有以下内容:
public void selectPhoto(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, CHOOSE_PHOTO);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CHOOSE_PHOTO:
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
((ImageView) findViewById(R.id.selImageView)).setImageBitmap(yourSelectedImage);
break;
}
}
编辑:我已经缩小了上述代码的错误来源。当用户提示从图库中选择一张照片时,会发生崩溃,但随后按下而不是选择照片并尝试返回应用程序。有什么想法吗?
答案 0 :(得分:1)
在你的onActivityResult中,你没有检查resultCode以查看结果是否被取消。然后你就像图像被传递一样继续。最有可能的是,因为resultCode将指示取消,您的selectedImage变量为null,而openInputStream不喜欢打开流。
此外,在抛出异常之后,您将null imageStream传递给decodeStream方法。
尝试类似:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CHOOSE_PHOTO:
if (resultCode = Activity.RESULT_OK) {
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
((ImageView) findViewById(R.id.selImageView)).setImageBitmap(yourSelectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
// handle cancelation
}
break;
}
}