【问题标题】:Occasional crash on Android when loading images?加载图像时Android偶尔崩溃?
【发布时间】:2013-07-16 17:30:15
【问题描述】:

我有一个我仍在研究的机制,我正在尝试消化代码,并且我已经从各种来源获得了我所拥有的东西。基本上有一个 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;
    }
}

编辑:我已经缩小了上面代码的错误来源。当用户提示从图库中选择一张照片,但随后按下返回而不是选择一张照片并尝试返回应用程序时,就会发生崩溃。任何想法为什么?

【问题讨论】:

  • 您应该尝试检查 logcat,然后在此处发布日志,以便人们可以帮助您更有效地调试! =]

标签: android imageview forceclose


【解决方案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;
  }
}

【讨论】:

  • 是的,我使用了类似的解决方案。我确实有跟进;如果我使用 CHOOSE_PHOTO 选项并选择一张照片,则可以。如果我第二次 CHOOSE_PHOTO 并选择另一张照片,应用程序会崩溃;知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
相关资源
最近更新 更多