Issue
Consider the fact that you have an API that you're getting data from, and the API itself returns certain keys that the receiving client should use to "resolve" which human-readable string to present to the user.
For example, the keys may look something like this:
DOMAIN_TYPE_SUBTYPE_ID
and would then correspond to a given entry in strings.xml:
<string name="domain_type_subtype_id">This magical item</string>
Unfortunately, the human-readable values themselves aren't passed from the API (nor have the need to be translated), but I'm trying to figure out the best approach as to how to map the keys to the values (R.string.abc) in the most efficient manner.
Off the top of my head, I see two ways going forward (as I can't change the API):
1) Doing a runtime resource lookup based on the name and pray to all the code gods that things don't change. Basically:
Resources.getSystem().getIdentifier(keyFromTheApi.toLowerCase(), "id", getPackageName())
However, from what I've heard and read... that's really not a performant way to do it. I reckon using that in a RecyclerView setting for multiple strings would be a really bad idea.
2) Have a static lookup field somewhere in a singleton class with all the data (String, Integer), but given the fact that there are a lot of keys to keep track of, that might be an unfortunate memory hit?
Map<String, Integer> strings = new HashMap<String, Integer>() {{
put("DOMAIN_TYPE_SUBTYPE_ID", R.string.domain_type_subtype_id);
//...
}};
🤔
Any suggestions on how to approach the problem in a good way?
Solution
Feels really fragile, I'd avoid it
I'd do something similar but with a switch statement instead:
public static int lookupStringRes(String value) { switch (value) { case "DOMAIN_TYPE_SUBTYPE_ID": return R.string.domain_type_subtype_id; // ... default: Log.w("TAG", "Resource not found"); return -1; } }
Not saying this is the best solution, but off the top of my head, it's the solution I would start with. Map vs Switch kind of comes down to memory vs performance, you'll have a faster lookup in the Map at the cost of memory.
Answered By - patrick.elmquist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.