1

我想处理当imageView尝试从用户先前删除的本地文件中打开图像并改为显示默认图像时的情况。为此,我尝试:

int flag = 0;
try{
        img_car.setImageURI(Uri.parse(path_picture));
        flag = 1;
    }
catch(Exception e){ //if I put FileNotFoundException I get error: Unreachable catch block for FileNotFoundException. This exception is never thrown from the try 
// statement body
        Log.i("TAG EXCEPTION PIC", e.getMessage());
        img_car.setImageResource(pictureId);
    }

img_car.setImageResource(pictureId);img_car.setImageURI(Uri.parse(path_picture));(当图片实际存在时)都有效。

我的问题是抓不到异常(当图片不存在时),基本上这个子句不会抛出它。(我的LogCat不显示任何信息日志消息)。即便如此,LogCat显示java.io.FileNotFoundException

 09-06 13:12:22.066: W/ImageView(27274): Unable to open content:
 file:///storage/sdcard0/folder_name/my_image.PNG
 09-06 13:12:22.066: W/ImageView(27274): java.io.FileNotFoundException:
 /storage/sdcard0/folder_name/my_image.PNG: open
 failed: ENOENT (No such file or directory) 09-06 13:12:22.066:
 W/ImageView(27274):    at libcore.io.IoBridge.open(IoBridge.java:416)
 09-06 13:12:22.066: W/ImageView(27274):    at
 java.io.FileInputStream.<init>(FileInputStream.java:78) 09-06
 13:12:22.066: W/ImageView(27274):  at
 java.io.FileInputStream.<init>(FileInputStream.java:105) 09-06
 13:12:22.066: W/ImageView(27274):  at
 android.content.ContentResolver.openInputStream(ContentResolver.java:445)
 09-06 13:12:22.066: W/ImageView(27274):    at
 android.widget.ImageView.resolveUri(ImageView.java:631) 09-06
 13:12:22.066: W/ImageView(27274):  at
 android.widget.ImageView.setImageURI(ImageView.java:379) 09-06
 13:12:22.066: W/ImageView(27274):  at
 com.myapp....

指向我的行:img_car.setImageURI。另一个奇怪的事情是,即使在上面的行上发生异常,该标志在执行1之后也有值try-catch,因此理论上不应执行该行。(对吗?)。任何帮助将不胜感激。谢谢!

4

2 回答 2

6

我退出了using try-catch,而是这样做了:

 Bitmap bitmap = BitmapFactory.decodeFile(path_picture);
            if(bitmap != null)
                imgdata.setImageBitmap(bitmap);
            else{
                imgdata.setImageDrawable(getResources().getDrawable(R.drawable.default_image));
            }

我首先将内容提取到位图中,如果位图为空,则加载默认图像。有用。

于 2013-09-09T10:19:29.310 回答
2

试试这个方法

int flag = 0;
try{
        img_car.setImageURI(Uri.parse(path_picture));
        flag = 1;
    }catch(Throwable e){ 

        img_car.setImageResource(R.drawable.img_car);
    }
于 2013-09-06T12:30:57.213 回答