0

What I am trying to achieve is when a new user registers I would like to run a query to make sure that the username which they have selected doesn't already belong to some other user. To do this I have written the register(); method, but it's not giving me back anything, not the Toast message indicating that the username has already been taken, nor does it take me to the next page indicating that the email has been sent and the user has to now log in.

Can someone explain to me what I am doing wrong?

RegisterActivity

private void register(final String username, final String fullname, String email, String password) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean ifUsernameExists = false;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    if (user != null) {
                        if (username.equals(user.getUsername())) {
                            Toast.makeText(RegisterActivity.this, "That username has already been taken. Try another", Toast.LENGTH_SHORT).show();
                            ifUsernameExists = true;
                        }
                    }
                }

                if (!ifUsernameExists) {
                    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegisterActivity.this, task -> {
                        if (task.isSuccessful()) {
                            sendVerificationEmail();
                            FirebaseUser firebaseUser = mAuth.getCurrentUser();
                            String userid = firebaseUser.getUid();

                            mReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);

                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("id", userid);
                            hashMap.put("email", email);
                            hashMap.put("username", username.toLowerCase());
                            hashMap.put("fullname", fullname);
                            hashMap.put("bio", "");
                            hashMap.put("imageurl", "https://firebasestorage.googleapis.com/v0/b/events-50eda.appspot.com/o/Placeholder.png?alt=media&token=0e651fa8-32e9-4f42-be9a-a5365f44b0f4");

                            mReference.setValue(hashMap).addOnCompleteListener(task1 -> {
                                if (task1.isSuccessful()) {
                                    FirebaseAuth.getInstance().signOut();
                                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                }
                            });
                        } else {
                            Toast.makeText(RegisterActivity.this, "You can't register with that email", Toast.LENGTH_LONG).show();
                            mProgressDialog.dismiss();
                        }
                    });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
JMB
  • 313
  • 2
  • 9
  • You can check **[this](https://stackoverflow.com/questions/47893328/checking-if-a-particular-value-exists-in-the-firebase-database/47893879)** out. – Alex Mamo May 26 '20 at 10:12
  • 1
    @AlexMamo I figured out that actually my entire problem was Firebase rules. I had to change them, but actually the code worked. Thanks for the tips though. Now I just have to figure out how to allow a non-authenticated user to be able to read and write to the Firebase… Thanks for the help, Alex! – JMB May 27 '20 at 08:17
  • @AlexMamo I guess you answered the Firebase Security rule dilemma, but what if I didn't want to create a separate node for Usernames. What if I just wanted to use a for loop and look through all the usernames? Like I said the method I wrote works, I just need to make it so an un-authenticated user can read to see if the username could possible exists and then write to the database, meaning save their data to Firebase. – JMB May 27 '20 at 08:21

2 Answers2

0

The value that you are looking for in the user variable is getting lost. I would print it out ar run a debug to check where I am losing it.

Thomas Lazer
  • 178
  • 6
0

The first part of the problem was solved according to OP's comment:

I figured out that actually my entire problem was Firebase rules.

Using the information in the answer from the following post:

What if I just wanted to use a for loop and look through all the usernames?

You cannot do that unless you are authenticated.

Like I said the method I wrote works, I just need to make it so an unauthenticated user can read to see if the username could possibly exist and then write to the database, meaning save their data to Firebase.

The only way in which unauthenticated users can read the data is to write the rules like this:

{
  "rules": {
      ".read": true,
      ".write": true
  }
}

But is not recommended because these security rules are defined as public, and anyone can steal, modify, or delete data in your database.

The simplest solution I can think of is to authenticate the user with email and password and provide the option the set the user name right after that. Once the user is already authenticated, you can use the query that you said it's working along with the existing security rules.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193