Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store Resource id in Database on Android

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.

like image 215
Fossor Avatar asked Jan 28 '14 09:01

Fossor


Video Answer


1 Answers

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.

like image 51
Vratislav Jindra Avatar answered Oct 27 '22 01:10

Vratislav Jindra