Java 按钮单击事件发生时,如何在 Android 中创建随机 UUID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28770408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create random UUID in Android when button click event happens?
提问by Raj De Inno
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.
我是 Android 的学徒。我需要制作随机 UUID 并作为主键存储到数据库中。我在按钮单击事件中使用 UUID.randomUUID.toString() 这段代码。UUID 已经有效地变得有趣。但是,如果我再次单击该按钮,则需要创建另一个 UUID。无论如何,我的代码不会生成新的 UUID。有人,当我点击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();
}
});
采纳答案by Fahim
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 条件
if(uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
}
Use this
用这个
uniqueId = UUID.randomUUID().toString();
回答by dishan
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. But when you click it next time uniqueId is not null, So no new UUID is generated.
当您第一次单击按钮时uniqueId
为空并生成一个新的 UUID。但是当您下次单击它时 uniqueId 不为空,因此不会生成新的 UUID。
回答by Juanjo Vega
You are explicitly avoiding the new UUID creation by:
您通过以下方式明确避免创建新的 UUID:
if(uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
}
Remove the check.
取下支票。
回答by DaleHyman
When you compare a String use .equals()
当您比较字符串时,请使用 .equals()
if(uniqueId.equals(null)) {
uniqueId = UUID.randomUUID().toString();
}