Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create random UUID in Android when button click event happens?

Tags:

java

android

uuid

I am an apprentice to Android. I need to make random UUID and store to the database as a primary key. I am utilizing UUID.randomUUID.toString() this code in Button click event. The UUID has been effectively made interestingly. Yet, in the event that I click the button once more, I need to make another UUID. In any case, my code is not making new UUID. Somebody, please help me to make an irregular UUID when I click catch.

Here is my code :

String uniqueId = null;
showRandomId = (Button)findViewById(R.id.showUUID);
showRandomId.setOnClickListener(new View.OnClickListener() {
  public void OnClick(View v) {
    if(uniqueId == null) {
       uniqueId = UUID.randomUUID().toString();
    }
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(getBaseContext(), uniqueId, duration);
    toast.show(); 
  }
});
like image 328
Raj De Inno Avatar asked Feb 27 '15 17:02

Raj De Inno


People also ask

Can random UUID collide?

A collision is possible but the total number of unique keys generated is so large that the possibility of a collision is almost zero. As per Wikipedia, the number of UUIDs generated to have atleast 1 collision is 2.71 quintillion.

How does UUID randomUUID work?

The randomUUID() method is used to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator.

How does UUID generate time based?

To generate time based UUIDs in maven project you have add the dependency of Generator that is generate time based UUIDs. If you have a normal java project you have to import library of Generator java-uuid-generator. Then generate the UUID: UUID uuid= Generators.


3 Answers

First time it intialise the variable and next time when you click button it doesn't get null value

Remove if condition from this

if(uniqueId == null) { 
uniqueId = UUID.randomUUID().toString(); 
}

Use this

uniqueId = UUID.randomUUID().toString(); 
like image 145
Fahim Avatar answered Oct 27 '22 17:10

Fahim


You are explicitly avoiding the new UUID creation by:

if(uniqueId == null) {
   uniqueId = UUID.randomUUID().toString();
}

Remove the check.

like image 39
Juanjo Vega Avatar answered Oct 27 '22 16:10

Juanjo Vega


Your null check for uniqueId causes the problem.

when you click the button for the first time uniqueId is null and a new UUID is generated. But when you click it next time uniqueId is not null, So no new UUID is generated.

like image 5
dishan Avatar answered Oct 27 '22 17:10

dishan