Search code examples
javaandroiduuid

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


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

Solution

  • 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();