我正在制作社交媒体应用。在应用程序中,每个用户都有唯一的用户名。但我不是要用户选择用户名。我不是强迫用户选择用户名,而是根据用户名生成随机的用户名。
例如
String a = name.getText.ToString();
int b = Random();
String username =a+b;
但是我目前在用循环检查用户名时遇到问题。我的意思是,如果我的随机生成的用户名已经存在,只需生成另一个随机用户名,并检查它是否也退出。
final boolean[] durum = {false};
while(durum[0] ==false){
String usernameilk = namesurname.getText().toString().replace(" ","").replace("ç","c").replace("ğ","g").replace("ı","i").replace("ö","o").replace("ş","s").replace("ü","u").toLowerCase();
int random = randomInt();
String stringsayı=Integer.toString(random);
final String usernameson = usernameilk+"."+stringsayı;
database.child("users").child(usernameson).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
user.setPassword(password.getText().toString());
user.setEmail(email.getText().toString());
user.setNamesurname(namesurname.getText().toString());
durum[0] =true;
progressDialog.hide();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
我想要这样的东西;
for (int i = 0; i < 10000; i++) {
int random = randomInt();
String randomusername = namesurname.getText().toString()+random;
database.child("users").child(randomusername).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
//if random username is not exist create user and finish loop
database.child("users").setValue(user);
break;
//but if its exist then countinue loop
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 0 :(得分:0)
使用这种用户名已经存在
Query q = yourRef.orderByKey().limitToLast(1);
然后以
的身份执行此查询q.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) { // check to prevent null pointer exception
ID = Integer.parseInt(dataSnapshot.getKey().toString().replaceAll("[\\D]", ""));
//ID will have the recent added username's integerpart So
increment in the value and set the value under this username or what
ever you want to do
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(addDealActivity.this, "Something is Wrong Check Data Connection...", Toast.LENGTH_SHORT).show();
}
});
希望它有助于Happy编码