0

I have over 100 images in my drawable. Its basically a Category. I am calling data from server where a column included category. My images were named as cat_image1, cat_image2, cat_image3 etc. The server sending the corresponding srting as Image1, Image2, Image3 etc respectively. I think its not the way what I am doing

String catString = someJSONObject.getString(Config.POI_CATEGORY);

if (catString == "image1") {
    someView.setImage(getResources().getDrawable(R.mipmap.image1));
}

else if (catString == "image2") {
        someView.setImage(getResources().getDrawable(R.mipmap.image2));
    }

else if (catString == "image3") {
        someView.setImage(getResources().getDrawable(R.mipmap.image3));
    }

... 
... 
...
Devil's Dream
  • 655
  • 3
  • 15
  • 38
  • you cant compare string like that , change with this if(catString.equals("image1")) { // do your stuff } – Jhaman Das Apr 12 '16 at 12:00
  • Possible duplicate of [How to access resource with dynamic name in my case?](http://stackoverflow.com/questions/6583843/how-to-access-resource-with-dynamic-name-in-my-case) – Kevin Robatel Apr 12 '16 at 12:00
  • I think you should store these 100 images on your server and return the url of these images and then set that image accordingly – Alok Gupta Apr 12 '16 at 12:00

1 Answers1

1

Try something like this:

// catString = cat -> R.drawable.cat
int imageId = getResources().getIdentifier(catString, "drawable", getPackageName());
someView.setImage(imageId));

If you need a prefix use this:

// catString = cat -> R.drawable.ic_cat
int imageId = getResources().getIdentifier("ic_" + catString, "drawable", getPackageName());
someView.setImage(imageId));

You can also use a HashMap:

HashMap<String, Integer> hm = new HashMap<>();
// Put elements to the map
hm.put("cat", R.drawable.ic_some_cat_image);
hm.put("other cat", R.drawable.ic_other_cat);

for (int i = 0; i < typeofplace.length; i++) {
    // You might want to check if it exists in the hasmap
    someView.setImage(hm.get(catString));
}
Tom Sabel
  • 3,935
  • 33
  • 45
  • I forgot another thing. I had a prefix like "ic_image1" in drawable. Then how can I call it? – Devil's Dream Apr 12 '16 at 12:15
  • 1
    See edit, you can also use for example `HashMap`. Or you can prefix the drawable name `getResources().getIdentifier("ic_" + catString, "drawable", getPackageName())` – Tom Sabel Apr 12 '16 at 12:24