2

For my Android project, I am using the getID() method to retrieve the numeric value for a View and store this value in my database. I am banking that this getID() method for a particular View will always return the same constant value over multiple executions in a production environment and over subsequent application changes over years. Is my assumption correct?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
user1005585
  • 285
  • 5
  • 17
  • Aren't the IDs generated by the tools? Unless you can explicitly set an ID's *value* I would not count on relying on consistent behavior of the numeric value itself. – Dave Newton Aug 14 '12 at 16:43
  • I don't recommend using `if(view.getId() == 0x07010001)` since that may change, but using `if(view.getId() == R.id.view)` is safe. – Sam Aug 14 '12 at 16:50

1 Answers1

2

View#getId() is the value of R.id.xyz you define in your layout xml files. They don't change until you recompile your app since that changes the generated R.java file (not necessarily changing the numeric id value though).

over multiple executions in a production environment

yes, if the app is not updated

and over subsequent application changes over years

maybe, but I would not assume that. There is maybe a way to setup your tools to generate predetermined fix id values since Android itself has stable resource ids but Idk how that is done.

zapl
  • 63,179
  • 10
  • 123
  • 154
  • Thanks zapl. I didn't have a good feeling relying on getID() over future application and Android SDK changes. I'm glad I asked now. – user1005585 Aug 14 '12 at 16:50
  • Sam, Yes, I am comfortable with "if(view.getId() == R.id.view)", but I am actually storing R.id.View (which returns 0x07010001) in my database for future reference and I think I'm asking for trouble. Thanks for clearing that up. – user1005585 Aug 14 '12 at 16:55
  • 2
    For ids to be constant across builds you have to declare ids in public.xml(http://stackoverflow.com/questions/9348614/what-is-the-use-of-the-res-values-public-xml-file-on-android) – nandeesh Aug 14 '12 at 17:03
  • @user1005585 I found this comment by change, please read [Markdown: Comment Formatting](http://stackoverflow.com/editing-help/#comment-formatting) for some tips and tricks in Stack Overflow. – Sam Aug 14 '12 at 17:03
  • Nandeesh, very interesting. I like it. Thank you. – user1005585 Aug 14 '12 at 17:06
  • @Sam Thanks. I'll do that from now on. – user1005585 Aug 14 '12 at 17:21