I want to handle the case when an imageView
tries to open an image from local files that was previously deleted by the user and display a default image instead.
For this I try:
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);
}
Both img_car.setImageResource(pictureId);
and img_car.setImageURI(Uri.parse(path_picture));
(when the picture physically exists) work.
My problem is that I can't catch the exception (when the picture does not exists), basically this clause does not throw it.(My LogCat
does not display any info log message). Even that, LogCat
displays 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....
pointing me to the line: img_car.setImageURI
. Another strange thing is that the flag has the value 1
after the try-catch
is executed even the exception occours on the line above so theoretical this line shouldn't be executed.(right?). Any help will be highly appreciated. Thank you!
I quit using try-catch
and instead did this:
Bitmap bitmap = BitmapFactory.decodeFile(path_picture);
if(bitmap != null)
imgdata.setImageBitmap(bitmap);
else{
imgdata.setImageDrawable(getResources().getDrawable(R.drawable.default_image));
}
I extract first the content into a bitmap and if bitmap is null then load default image. It works.