简体   繁体   English

我想创建唯一的用户ID

[英]I want to create unique user id

I just create unique id but with random number. 我只是创建唯一的ID,但使用随机数。 but I want to create that id like jason-001,smith-002,etc. 但我想创建该ID,例如jason-001,smith-002等。

Integer user_id= new Random().nextInt();

//implementation
reference_uploaded_by.getRef().setValue(name.getText().toString() + "-" + user_id);

You can use AtomicLong#incrementAndGet as a counter. 您可以将AtomicLong#incrementAndGet用作计数器。 The “Atomic” means the class is thread-safe . “原子”表示该类是线程安全的

AtomicLong userIdIncrementor = new AtomicLong(previouslyUsedNumber);

Use that object to get incrementing numbers for each new user. 使用该对象获取每个新用户的递增编号。

long number = userIdIncrementor.incrementAndGet();
String userId = userName + String.format("%03d", number);

This code assumes you will never have more than a thousand users, with only three digits for the number as you specified in your Question. 此代码假定您永远不会有超过一千个用户,并且您在“问题”中指定的号码只有三位数字。

For details on formatting an integer, see this Answer . 有关格式化整数的详细信息,请参见此答案

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

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