Axelle
Axelle

Reputation: 472

set image with setImageResource in Android Studio using a variable

I am trying to set my image in my ImageView through a variable (item is the variable name, which I will be setting to lowerCase). However, it is not working and resID will return 0.

Here is my code:

    ImageView iv = (ImageView)v.findViewById(R.id.imgView);

    if (item != null) {
        Log.i("item: ", item.toLowerCase());

        int resID = getResources().getIdentifier(item.toLowerCase(), "drawable", "package.name");

        Log.i("resid: ", String.valueOf(resID)); //will return 0 - im guessing this is where the problem is

        iv.setImageResource(resID);
    }

I used this as a guide Android, reference things in R.drawable. using variables? but none of the other solutions work for me, in fact they all gave me the same result (returning 0). I can provide more code if needed (just didn't want it to be bombastic). Thanks in advance!

Upvotes: 1

Views: 2455

Answers (1)

Lior
Lior

Reputation: 842

getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)

and you should getPackageName() method of the context object which always return the correct package name.

if you will show your folder stracture and file's names i can help you to fix it.

btw, if you can get the drawable directly from the resource you can just use R.drawable.resName

Upvotes: 1

Related Questions