在Android上的数据库中存储资源ID的最佳方法 [英] Best way to store Resource id in Database on Android

查看:252
本文介绍了在Android上的数据库中存储资源ID的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我希望能够在数据库中存储某些图标的资源ID.我想这样做是不省钱的,因为在以后的阶段(应用程序升级),我可能想向应用程序添加新图标,所以所有ID可能会改变吗?如果我不想将图标存储为Blob,最好的存储资源方法是什么?

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?

作为一个例子,假设我有一个游戏1.0,我让用户从头像列表中为他的角色选择一个头像.我想将此头像ID存储在DB中,并确保如果在游戏1.1中添加更多头像,用户仍会看到他的选择.

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.

推荐答案

(我认为)最好的方法是存储资源条目名称.

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

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

因此您要在其中存储图标的SQLite数据库列的类型将为TEXT.没错,存储资源ID是一种错误的做法,因为在编译应用程序时会重新创建它们,因此您不能依靠它们不变(我很难学,所有应用程序的图标都弄乱了).

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).

要在需要时从字符串获取资源ID,请调用

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

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

请注意,getResources()getPackageName()都是Context中的方法,因此您需要引用您的应用程序/活动上下文才能调用这些方法.

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.

这篇关于在Android上的数据库中存储资源ID的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆