I had a problem where I needed to map some keys received from a website to image id's in my android app.
The solution I initally came up with was to use switch statements like so:
switch (weather_type) {
case "cloudy":
return R.drawable.cloudy;
case "rainy":
return R.drawable.rainy;
// etc
}
This is good and works great, but I was thinking if there was a way to store this information in XML and have it available at runtime. I was thinking something like a map in XML that lets me map the names to the actual resource, but since I'm still learning android, I'm not sure exactly how to go about doing this.
My plan then involved creating a string-array in xml to retrieve the values.
<string-array name="icon_map">
<item>cloudy:@mipmap/cloudy</item>
<item>rainy:@mipmap/rain</item>
</string-array>
In Java:
String []array = getResources().getStringArray(R.array.icon_map);
Log.i(TAG, array[0]);
Results in
1798-1798/com.practice.smac89.webstuff I/MainActivity cloudy:@mipmap/cloudy
When I was typing this in Android Studio, it was showing the actual images when I hover my mouse over the resources. So I was hoping that when I get this in the activity class, it would have been converted to the actual Id, but it wasn't.
TL;DR
Is there a way to store a mapping in xml where the value is a resource id and get the actual integer id in java? I was hoping for
1798-1798/com.practice.smac89.webstuff I/MainActivity cloudy:1231243
HashMap<String, Integer>, and have a method that populates it once when your app starts up.