1

I'm making a social media app. In app every user has a unique username. But I'm not asking the user to choose a username. Instead of forcing users to choose a username, I generate a random username based on users' name-surname.

for example

String a = name.getText.ToString();
int b = Random();
String username =a+b;

But I am currently having a problem checking username with loop. I mean, if my random generated username already exists, just generate another random username and check if it exists too.

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

I want something like this;

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) {}
    });
}
TheFabbius
  • 337
  • 4
  • 12
uzaysan
  • 583
  • 1
  • 4
  • 18
  • As addValueEventListener creates async task, it is not useful to encapsulate it with a while loop. Async task means completion of the process is not immediate and it will work in background. Therefore, when the onDataChange method will be called is ambigious. – Ziya ERKOC Aug 27 '18 at 21:05
  • I suggest you to think of a solution without any loop. – Ziya ERKOC Aug 27 '18 at 21:06
  • So basically what are you trying to achieve, is to see if a new generated uder already exist in your database? Please responde with @. – Alex Mamo Aug 28 '18 at 08:53
  • @AlexMamo i wanna check if my random generated username is alredy exist in firebase database. I save users like this; database.child("users").child("unique_username"); But i dont wanna use query based on my knowledge query spend alot of bandwitdh but my bandwidh is limited i wanna check wit java loops – uzaysan Aug 28 '18 at 18:20
  • @UzaySan Have you tried to use exists method? Have you seen my answer from this **[post](https://stackoverflow.com/questions/47893328/checking-if-a-particular-value-exists-in-the-firebase-database/47893879)**? – Alex Mamo Aug 28 '18 at 18:22
  • @AlexMamo yes i read your answer and i know exist method but i wanna do it in a loop for example my random username "alex123" check this username with exist method and if its not exist create a new user named alex123 nut if its exist then generate another random username like "alex143" and try again – uzaysan Aug 28 '18 at 18:28
  • No, the best way to verify if a users exists is to use my answer from that, not to query the entire database to see if only one user exist or not, right? – Alex Mamo Aug 28 '18 at 18:31
  • @AlexMamo actually we are talking about the same thing i will edit my question please take a look – uzaysan Aug 28 '18 at 18:35
  • I cannot see any edit, have you save it? – Alex Mamo Aug 28 '18 at 18:38
  • @AlexMamo i edited my question – uzaysan Aug 28 '18 at 18:50
  • This in not how thing work in Firebase. It is not a good practice to add 1000 listeners in order to get the data. Please also add the database structure. – Alex Mamo Aug 28 '18 at 18:55
  • @AlexMamo i give up i will try another way thank you for your effort – uzaysan Aug 28 '18 at 19:06

1 Answers1

0

Use this way of username already Exists there

Query q = yourRef.orderByKey().limitToLast(1);

then execute this query as

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

Hope it is helping Happy coding

Faiizii Awan
  • 1,615
  • 1
  • 13
  • 28
  • Thank you for your answer but as far as i know query spend alot of bandwidh but my bandwith is limited do you know how to do with loops? – uzaysan Aug 28 '18 at 18:23
  • Bandwidth is actually related to the data download and upload. when we specify limit to last then it only download the one result. whereas when we send this query to the server, the server will filters the result according to the query at server side which does not effect your bandwidth and when the contents is ready then it send the data to the client side. is one child effect your bandwidth ? – Faiizii Awan Aug 29 '18 at 10:34
  • moreover if you want to use loop then it may use a lot of resources like RAM,processor which may effect your app performance. but it can be done within loop too. if (datasnapshot not exists) { }else{ ID = Integer.parseInt(dataSnapshot.getKey().toString().replaceAll("[\\D]", "")); place this line in the else part and store the user by concatenating with ID } – Faiizii Awan Aug 29 '18 at 10:40