Reputation: 715
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));
}
...
...
...
Upvotes: 0
Views: 97
Reputation: 4025
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));
}
Upvotes: 1