Raj De Inno Raj De Inno - 4 months ago 10x
Java Question

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

I am a beginner to Android. I want to create random UUID and store to database as a primary key. I am using

this code in Button click event. The UUID has been successfully created for the first time. But if I click the button again, I want to create a new UUID. But my code is not creating new UUID. Someone please help me to create a random UUID when I click button.

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

Any help would be appreciated.


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