Using an array with a base adapter to populate a listview. There are over many optional drawables and so a switch case is highly inefficient. I've been trying to implement a two liner using getResources().getIdentifier() system but all attempts have failed returning resource id of 0 x 0000.
working code
try {
final ImageView star = convertView.findViewById(R.id.star);
final JSONObject object = list.getJSONObject(i);
switch (object.getString("star")){
case "a":
star.setImageResource(R.drawable.stara);
break;
case "b":
star.setImageResource(R.drawable.starb);
break;
case "c":
star.setImageResource(R.drawable.starc);
break;
case "d":
star.setImageResource(R.drawable.stard);
break;
}
I'm needing something using something like this but getIdentifier() method
final ImageView star = convertView.findViewById(R.id.star);
star.setImageDrawable(getActivity().getResources().getDrawable(getActivity().getResources().getIdentifier("star" + object.getString("star") + ".png", "drawable", getActivity().getPackageName())));
"star" + object.getString("star") + ".png" is the exact drawable name in resource folder (stara.png, starb.png, ....)
I keep getting this exception with getIdentifier() method
No package identifier when getting value for resource number 0x00000000
How to properly implement this or a better way using a programmatic string to determine the resource drawable name being set to an imageview?
You should be omitting the ".png". If you are looking for "stara.png", what you are trying to get is the idenfifier R.drawable.stara
, so what you should have is
getActivity().getResources().getIdentifier("star" + object.getString("star"), "drawable", getActivity().getPackageName())));