17

I have an android application that use a gallery component to choose an icon and assign it to a button.
The icon set is located in res/drawable folder and is accessed in the gallery with the typical adapter of the guide:

private Integer[] Imgid = {
   R.drawable.icon_home,
   R.drawable.icon_home2,
   ...
}

After an icon choosing, i stored the settings in a db with id of the button and of the drawable.
All works done, but i've noticed that if i'll want to add or modify my icon set or resources in general of my application, ids of old resource could change, so the preferences in the db refers to wrong icon.
Is there a way to force the old id of R class so they didn't change in the future? Or is there another way to manage the item of the component galley with another attribute than id? (maybe string name and reflection?)

Thanks in advance

zerkms
  • 230,357
  • 57
  • 408
  • 498
user842504
  • 325
  • 3
  • 8

3 Answers3

23

You can store the name of the drawable in the database if you don't plan to change that. getResourceEntryName returns the name from the resource id:

Resources resources = getResources();
String name = resources.getResourceEntryName(R.drawable.icon);

And you can get back the resource id from the name with getIdentifier:

int resId = resources.getIdentifier(name, "drawable", "your.package.name");
kriz
  • 601
  • 3
  • 5
  • 1
    thats the correct answer guys. android changes the ids of the r file dynamicly. if you want a static entry use the resource name as told by kriz. the id is not static and there is no way to make it static. – omni Dec 30 '11 at 14:17
2

You can't use static int for resource identifier, however you should look at two methods od Resources class:

getIdentifier()

getresourceName()

piotrpo
  • 11,607
  • 7
  • 38
  • 57
0

You shouldn’t rely on the actual values of the R.drawable.* attributes.
Create your own ids instead (for example 1 correspond to R.drawable.icon_home and 2 correspond to R.drawable.icon_home2)

Edit:
String name and reflection should work too, but it’s probably a little overkill you have only a few icons.

Guillaume Brunerie
  • 2,036
  • 1
  • 17
  • 28