Best way to store Resource id in Database on Android

﹥>﹥吖頭↗ 提交于 2019-12-03 08:37:06

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.

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