Tuesday, July 28, 2015

How do I generate GUID / UUID in android

GUID / UUID (Globally / Universally Unique Identifier) is frequently used in programming. There are many use of these UUID / GUID like, creating random file name, application id, unique id to store in database etc.

To generate UUID, Firstly we need to import java.util.UUID class in Activity class file. This class is introduced in JDK 1.5 version. You can use randomUUID() method to generate UUID. Here is the example of code. Take a look:

UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();

Log.v("Random UUID",randomUUIDString);
Log.v("UUID Version",uuid.version());
Log.v("UUID Varient",uuid.variant());


Code Explanation: 

First, We have created one uuid object and get random uuid. Its data type is also UUID. In next line of code, We have converted uuid into string format and stored in randomUUIDString object. Logs are displayed uuid,version and it's varient.

Output:

Random UUID   7dc53df5-703e-49b3-8670-b1c468f47f1f
UUID version     4
UUID variant      2


NOTE: UUID is randomly generated String so, It is not expected to get result same as above.



2 comments: