Android Question New to B4A, I need to generate Type 1 UUIDs

calloatti

Member
To upload data to a MySQL server, I need to generate Type 1 UUIDs to be used as primary keys. I have searched the forum but could not find any example code for doing this.

I have tried to roll my own but have been using B4A for only a couple of weeks, so I am not familiar enough to be able to do it on my own.

Thanks in advance for any hints that point me in the right direction.
 

Peter Simpson

Expert
Licensed User
Firstly welcome to the forum @calloatti,
I've used this in the past for V4 UUID, it works in both B4A and B4J and uses the Reflection library. There are plenty of examples on this forum that do not use the Reflection library.

B4X:
Sub UUID As String
    Dim Ref As Reflector
        Ref.Target = Ref.RunStaticMethod("java.util.UUID", "randomUUID", Null, Null)
    Return Ref.RunMethod("toString")
End Sub


Enjoy...
 
Last edited:
Upvote 0

calloatti

Member
Thank for the replies and the welcoming. I had found both examples by searching before posting, and its not exactly what I need, I should have explained myself better, my mistake.

It has to be a type 1 UUID since they are based on a timestamp and the mac address of the machine that generated it . What I really need in this case is what some call a Type 6 UUID, but it is trivial to generate a type 6 from a type 1. These links will explain it better than I could:


TLDR: They are used as primary indexes in tables. That's how the existing MySQL database I have to work with is designed, and that is what I have to provide. It cannot be a random uuid for the reasons explained in the links above.

I did find java libraries that generate type 1 uuids, I also found that java.util.UUID does generate type 1 uuids, but you have to provide the timestamp, and if I knew how to generate the timestamp used I would then just implement the uuid generation myself.

One java library I did come across is this one: https://github.com/f4b6a3/uuid-creator and it even generates type 6 uuids! Sadly I know java as much as I know B4A, so no chance of me creating a B4A library out of that for now.

This is the algorithm for a type 1 uuid if anyone is interested: https://datatracker.ietf.org/doc/html/rfc4122#section-4.2.1
 
Upvote 0

Erel

Administrator
Staff member
Licensed User
B4X:
#AdditionalJar: C:\Users\H\Downloads\uuid_creator.jar

Sub Test
    Dim uuidcreator As JavaObject
    uuidcreator.InitializeStatic("com.github.f4b6a3.uuid.UuidCreator")
    Dim uuid As JavaObject = uuidcreator.RunMethod("getTimeOrdered", Null)
    Log(uuid.RunMethod("toString", Null))
End Sub
MIT License: https://github.com/f4b6a3/uuid-creator
 

Attachments

  • uuid_creator.jar
    185.7 KB · Views: 12
Upvote 0
Top