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();
}
});
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.
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.
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.
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();
You are explicitly avoiding the new UUID creation by:
if(uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
}
Remove the check.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With