Runtime String to Long Conversion For Hashing

BlackBerry programming certainly has its peculiarities, and of them is the way you generate hash keys using a menu item in the Java Development Environment. If you want to persist an object, for example, you’ll need to generate a key to associate with the object in the persistent store. That key is used to retrieve the contents of the object from the persistent store the next time the application starts.

The way you normally generate such a key is to type in a unique string (usually the fully-qualified name of a class in your application) into the JDE text editor, select the string you just typed, right click on the selection, and then choose the Convert ‘yourstringhere‘ to long item from the popup menu:

This key generation method always seemed a bit peculiar to me. What if you wanted to generate a key dynamically at runtime? What if you weren’t using the JDE as your text editor?

Luckily, in BlackBerry API 4.0.2 they exposed the stringHashToLong method in net.rim.device.api.util.StringUtilities that generates the same keys that the JDE does. (The StringUtilities class is underappreciated, I think, and worthy of further discussion in a later post.) Runtime generation of hash keys is trivial with this method, but not a lot of people know about it.

Reference: net.rim.device.api.util.StringUtilities.stringHashToLong