简体   繁体   English

当按钮点击事件发生时,如何在Android中创建随机UUID?

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

I am an apprentice to Android. 我是Android的学徒。 I need to make random UUID and store to the database as a primary key. 我需要随机创建UUID并将其作为主键存储到数据库中。 I am utilizing UUID.randomUUID.toString() this code in Button click event. 我在Button click事件中使用UUID.randomUUID.toString()这段代码。 The UUID has been effectively made interestingly. UUID实际上非常有趣。 Yet, in the event that I click the button once more, I need to make another UUID. 然而,如果我再次单击该按钮,我需要制作另一个UUID。 In any case, my code is not making new UUID. 无论如何,我的代码没有制作新的UUID。 Somebody, please help me to make an irregular UUID when I click catch. 有人,当我点击catch时,请帮我制作一个不规则的UUID。

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

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

Your null check for uniqueId causes the problem. 您对uniqueId空检查会导致问题。

when you click the button for the first time uniqueId is null and a new UUID is generated. 当您第一次单击该按钮时, uniqueId为null并生成新的UUID。 But when you click it next time uniqueId is not null, So no new UUID is generated. 但是当下次uniqueId不为null时单击它,因此不会生成新的UUID。

You are explicitly avoiding the new UUID creation by: 您通过以下方式明确地避免了新的UUID创建:

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

Remove the check. 取消支票。

When you compare a String use .equals() 比较字符串时使用.equals()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM