Home » Android » java – how to create random UUID in Android when button click event happens?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

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(); 
  }
});
How to&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(); 

Answer:

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.

Answer:

You are explicitly avoiding the new UUID creation by:

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

Remove the check.

Answer:

When you compare a String use .equals()

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