'How to generate unique integer values in Java (Android) at compile time

I need lots of unique integers in my Android code, for example for intent request codes.

I don't want to have to worry about collisions, even if I move fragments between activities. So I want them to be globally unique.

At the moment, I am doing this manually.

    public static final int HTTP_ADD_OR_REMOVE_CALENDAR_REQUEST_CODE = 20001;

This is annoying and error prone. Is there a way to tell Android/Java:

"I want a unique integer here, please set it at compile time" ?

Of course I'd rather use an enum, but apparently that's not the Android way...



Solution 1:[1]

An ID resource will give you an integer that does not collide with any other ID resources used in your app (e.g., for widget IDs in a layout resource).

Solution 2:[2]

Create an enum. Then you just add a new item to the enum.

You don't want to assign these at compile time. Half the point of these ids is to make it easy when using a debugger to be able to tell what the id is and figure out what the matching constant is. Assigning at compile time makes that a nightmare. It will cost you a TON of time in maintenance down the line. You'd be trading seconds at time of writing for hours of time in maintenance.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CommonsWare
Solution 2 Gabe Sechan