Development Zeast
Development Zeast

Reputation: 21

Resources.NotFoundException is thrown while loading many images in a loop

I am displaying almost 4,000 images in a loop with image name.

Here is the code which i am using to get my images from drawable folder

     for(int i=0; i<count(images_array); i++) {
            mDrawableName = images_array(i);

            int resID = res.getIdentifier(mDrawableName, "drawable", activity.getPackageName());
            Drawable drawable = res.getDrawable(resID);
            image.setImageDrawable(drawable);
     }

the issues are:

  1. When the image name is not found in resource folder my app throws me an exception and crashes.
  2. Is there any better way to load 4000 images from drawable in listview? Is there any way i can check if image is not in drawable then show placeholder image ?

Upvotes: 0

Views: 120

Answers (2)

Development Zeast
Development Zeast

Reputation: 21

 Boolean fileFound = true;
        try{
            int resID = res.getIdentifier(mDrawableName , "drawable", activity.getPackageName());
            Drawable drawable = res.getDrawable(resID );
            image.setImageDrawable(drawable );
        }catch (Resources.NotFoundException e){
                fileFound = false;
        }
        if(!fileFound){
            int resID = res.getIdentifier("img_not_found" , "drawable", activity.getPackageName());
            Drawable drawable = res.getDrawable(resID );
            image.setImageDrawable(drawable );
        }

Upvotes: 0

Gino Mempin
Gino Mempin

Reputation: 29570

When the image name is not found in resource folder my app through me an exception and crash.

This is not an issue since it is expected behavior that getIdentifier returns 0 for a non-existent resource and then getDrawable throws the Resources.NotFoundException for id = 0 (which is not a valid ID).

Is there any way i can check if image is mot in drawable then show placeholder image?

You either catch that exception or check if getIdentifier returned 0.
I don't know the rest of your code, so based on what you posted, you could do this:

for (int i=0; i<count(images_array); i++) {
    mDrawableName = images_array(i);

    int resID = res.getIdentifier(mDrawableName, "drawable", activity.getPackageName());
    Drawable drawable;
    if (resID == 0) {
        drawable = res.getDrawable(R.drawable.placeholderimage, null);
    } else {
        drawable = res.getDrawable(resID);
    }
    image.setImageDrawable(drawable);
}

Note:
getDrawable(int id) is now deprecated starting API 22.
In the sample code, I used getDrawable(int id, Resources.Theme theme) instead.
You might want to check out the other alternatives.

Is there any better way to load 4000 images from drawable in listview?

Try using Android's RecyclerView and/or 3rd-party libs such as Glide.

Upvotes: 1

Related Questions