0

I have a model and it has a specific country flag:

public int getCountryFlag() {
    return countryFlag;
}

public void setCountryFlag(int countryFlag) {
    this.countryFlag = countryFlag;
}

I am getting Data from an API. The API has a value country code and this could be like: "country":"de","created_at":"2018-08-08 09:17:43","updated_at":"2018-08-08 09:17:43"

I have the flags named as the country code:

de
se
us
....

How can I get the exact resourceID of the image to relate it to the model? I am using RecyclerView.

I tried something like:

int resID = getResources().getIdentifier(object.getString("country"), "drawable",  getPackageName());
model.setCountryFlag(R.drawable.sy);

Though that didn't work!

InsaneCat
  • 2,115
  • 5
  • 21
  • 40
Mike
  • 111
  • 1
  • 10

2 Answers2

0

If you're sure about the format of the api string then do the following:

String country = api.trim().split(",")[0].split(":")[1].replaceAll("\"", "");

or

String country = api.trim().substring(11, 13);

and then:

int resID = getResources().getIdentifier(country, "drawable",  getPackageName());
model.setCountryFlag(resID);
  • I am sure about the format of the API and I get the value of 0 always. So it's an exception error – Mike Aug 08 '18 at 10:38
  • @Mike So if you use `String country = api.substring(11, 13);` do you get the 2 letters for the country? –  Aug 08 '18 at 10:41
  • Oh damn! This is working actually. I had forgotten to rename the file. I simply didn't have it correct in the folder. Thanks man :)) – Mike Aug 08 '18 at 10:44
  • Fine___________ –  Aug 08 '18 at 10:45
0

You can get flag by Resource Id name

int drawableResourceId = this.getResources().getIdentifier("de", "drawable", this.getPackageName());

you can also check How to get a resource id with a known resource name?