简体   繁体   English

将密钥从服务器映射到资源

[英]Map keys from the server to resources

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. 请考虑以下事实:您拥有从中获取数据的API,并且API本身返回某些密钥,接收方客户端应使用这些密钥“解析”要呈现给用户的人类可读字符串。

For example, the keys may look something like this: 例如,键可能看起来像这样:

DOMAIN_TYPE_SUBTYPE_ID

and would then correspond to a given entry in strings.xml : 然后对应于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. 不幸的是,人类可读的值本身并没有从API传递(也不需要翻译),但是我试图找出关于如何将键映射到值的最佳方法( R.string.abc )以最有效的方式。

Off the top of my head, I see two ways going forward (as I can't change the API): 我不由自主地看到了两种前进的方式(因为我无法更改API):

1) Doing a runtime resource lookup based on the name and pray to all the code gods that things don't change. 1)根据名称进行运行时资源查找,并向所有代码神祈祷,事情不会改变。 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. 我认为在RecyclerView设置中为多个字符串使用它是一个非常糟糕的主意。

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? 2)在单例类中的所有数据(字符串,整数)的某个位置都有一个静态查找字段,但是鉴于存在很多要跟踪的键的事实,这可能是不幸的内存命中了吗?

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? 关于如何以良好方式解决问题的任何建议?

  1. Feels really fragile, I'd avoid it 感觉真的很脆弱,我会避免

  2. I'd do something similar but with a switch statement instead: 我会做类似的事情,但是要用switch语句:

     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. Map vs Switch归结为内存与性能之间的关系,您将以内存为代价在Map中进行更快的查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM