B4J Code Snippet Generate UUID in B4J

I know this is very late. But I'd like to share my working code to generate UUID in B4J. As a requirement, must select from the Library: JavaObject.
GenerateUUID:
Sub GenerateUUID() As String
    Dim jObj As JavaObject
    jObj.InitializeStatic("java.util.UUID")
    Dim uuid As String = jObj.RunMethod("randomUUID", Null)
    Return uuid
End Sub
 

Lucas Siqueira

Active Member
Licensed User
Longtime User
for b4x use:

The previous code fixed the character 8 in the first position of the fourth group of characters. Now it can be 8, 9, a, or b

B4X:
Sub UUIDv4 As String
    ' Initializes a StringBuilder to construct the UUID string
    Dim sb As StringBuilder
    sb.Initialize

    ' Defines the format of the UUID with 5 groups (8, 4, 4, 4, 12 characters respectively)
    For Each stp As Int In Array(8, 4, 4, 4, 12)
        ' Adds a hyphen (-) between groups, except before the first group
        If sb.Length > 0 Then sb.Append("-")

        ' Iterates through the number of characters in each group
        For n = 1 To stp
            ' Generates a random number between 0 and 15 (hexadecimal)
            Dim c As Int = Rnd(0, 16)

            ' Converts the random number into a hexadecimal character (0-9 or a-f)
            If c < 10 Then 
                c = c + 48 ' Converts numbers 0-9 to their ASCII values (48 = '0')
            Else 
                c = c + 87 ' Converts numbers 10-15 to their ASCII values ('a'-'f', 87 is the offset)
            End If

            ' If we're at the start of the fourth group (sb.Length = 19), adjusts the first character
            ' This value must be 8, 9, a, or b, as defined by the UUID v4 specification
            If sb.Length = 19 Then
                ' Creates an array containing the possible values for the first character of the fourth group
                Dim variantArray() As String = Array As String("8", "9", "a", "b")
                ' Randomly selects one value from the array and converts it to ASCII
                c = Asc(variantArray(Rnd(0, variantArray.Length)))
            End If

            ' If we're at the start of the third group (sb.Length = 14), defines the UUID version as 4
            ' This is required by the UUID v4 specification
            If sb.Length = 14 Then 
                c = Asc("4") ' Sets the character to "4", indicating version 4
            End If

            ' Appends the generated character to the StringBuilder
            sb.Append(Chr(c))
        Next
    Next

    ' Returns the complete UUID string, converted to lowercase
    Return sb.ToString.ToLowerCase
End Sub


 
Last edited:

TILogistic

Expert
Licensed User
Longtime User
With the solution proposed above I had problems with duplicate UUIDs.

With this one I have not had problems with duplicate UUIDs, in Java 11 or higher it generates version 4.
 
Last edited:
Top