68

I'm retrieving custom Resource IDs from a custom xml view type. I'm asked to specify a default int value for the retrieval and was wondering what is the range of IDs? Are they always positive or do they include zero??

i.e is -1 a valid "null" reference AND/OR is 0 a valid "null" reference?

Thanks

EDIT

Custom XML resource/attribute file

<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="onImage" format="integer" />
        <attr name="offImage" format="integer" />
    </declare-styleable>
</resources>

Defined in my constructor for my custom ui

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);

int offResource = a.getInt(R.styleable.ToggleImageButton_offImage, -1);

Basically the -1 at the end of the 2nd line is the default parameter for this data type. It may or may not be initialized in the XML view when developing and this allows default behavior to be specified this way.

Kurru
  • 14,180
  • 18
  • 64
  • 84
  • -1 should be safe enough, although I can't find any document about this. – xandy Feb 27 '11 at 01:28
  • Aren't XML based resource ID's always generated automatically and stored in R.java? What do you mean "I'm asked to specify a default int value" - it would help if you will show the line(s) of code. – DJC Feb 27 '11 at 01:30
  • @DJC, Android prefer default value than throwing exception, in case of retrieving Non-nullable values. – xandy Feb 27 '11 at 01:32

3 Answers3

101

According to the documentation, Resources.getIdentifier()

Returns 0 if no such resource was found. (0 is not a valid resource ID.)

UPDATE (after 5+ years thanks to Micer):

  • API 29+: Resources.ID_NULL constant
  • older API: ResourcesCompat.ID_NULL
Ewoks
  • 12,285
  • 8
  • 58
  • 67
  • It is best to use `ID_NULL` as mentioned by @Micer. – ThomasW Oct 15 '20 at 01:56
  • As mentioned by a few people here, use the Resources.ID_NULL constant for API 29+. For previous versions, use ResourcesCompat.ID_NULL. Or just use 0 if you're in a silly goofy mood. – David Read Sep 23 '21 at 16:11
13

0 is a null/invalid value for a resource ID.

adamp
  • 28,862
  • 9
  • 81
  • 69
4

According to https://developer.android.com/reference/android/content/res/Resources#ID_NULL, 0 is the same as setting @null in XML, meaning you can use it i.e. when you want to clear the resource.

It is an invalid resource ID.

Micer
  • 8,731
  • 3
  • 79
  • 73