【问题标题】:how to create random UUID in Android when button click event happens?发生按钮单击事件时如何在Android中创建随机UUID?
【发布时间】:2015-02-27 17:01:57
【问题描述】:

我是 Android 的学徒。我需要制作随机 UUID 并作为主键存储到数据库中。我在按钮单击事件中使用 UUID.randomUUID.toString() 这段代码。 UUID 已经被有效地制作得非常有趣。然而,如果我再次单击该按钮,我需要创建另一个 UUID。无论如何,我的代码都没有创建新的 UUID。有人,请在我单击捕获时帮我制作一个不规则的 UUID。

这是我的代码:

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

【问题讨论】:

  • if(uniqueId == null) { 我猜你在类而不是方法中拥有它? uniqueId 已设置,由于上面的行,它不会创建一个新的

标签: java android uuid


【解决方案1】:

第一次初始化变量,下次单击按钮时它不会得到空值

从这里删除 if 条件

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

使用这个

uniqueId = UUID.randomUUID().toString(); 

【讨论】:

    【解决方案2】:

    您通过以下方式明确避免创建新的 UUID:

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

    取消勾选。

    【讨论】:

      【解决方案3】:

      您对uniqueId 的空检查会导致问题。

      当您第一次单击按钮时,uniqueId 为 null 并生成新的 UUID。但是下次点击时uniqueId不为null,所以不会生成新的UUID。

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 1970-01-01
        • 2011-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-03
        • 1970-01-01
        • 2014-05-04
        相关资源
        最近更新 更多