Best way to store Resource id in Database on Android

浪子不回头ぞ 提交于 2019-12-04 14:49:13

问题


In my app i want to be able to store resource id of some icons in database. I suppose it is not save to do, cause in the later stages (application upgrades) i may want to add new icons to the app, so all id's may change? What is the best practice to store resource in case i do not want to store icons as blobs?

As an example, let's say i have a game 1.0, where i let user to choose an avatar for his character from a list of avatars. I want to store this avatars id in DB and be sure that if i add more avatars in game 1.1 - user will still see his choice.


回答1:


The best way (in my opinion) is to store the resource entry name.

String iconName = getResources().getResourceEntryName(R.drawable.your_icon);

So your SQLite database column where you want to store the icon will have type TEXT. You're right that storing resource IDs is a bad practice because they're recreated when you compile the app, so you can't rely on them not changing (I learned this the hard way, all my app's icons got messed up).

To get the resource ID from the String when you need it, call

int resID = getResources().getIdentifier(iconName, "drawable", getPackageName());

Note that both getResources() and getPackageName() are methods from Context, so you need to have reference to your application/activity Context to be able to call these methods.



来源:https://stackoverflow.com/questions/21402275/best-way-to-store-resource-id-in-database-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!