0

I need that if a person registers and enters a nickname that exists, it is checked and written that such a nickname already exists:

enter image description here

For example, I created an account. And so, we have an account with the nickname "Creator", and I want that if the next person wants to make the same nickname, then the system would write to him that such a nickname already exists. I know how to make the system write to him, just how to check that such a nickname already exists.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Biron1gg
  • 87
  • 1
  • 10
  • @AliasCartellano i need Java – Biron1gg Jul 09 '22 at 16:28
  • Try looking at [Checking if a particular value exists in the Firebase Database](https://stackoverflow.com/a/47893870/16653700). – Alias Cartellano Jul 09 '22 at 16:48
  • 3
    Does this answer your question? [Prevent duplicate entries in Firestore rules not working](https://stackoverflow.com/questions/54236388/prevent-duplicate-entries-in-firestore-rules-not-working) – ErnestoC Jul 11 '22 at 17:28

1 Answers1

0

To check if the name "Creator" is already taken or not, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
Query userNameQuery = usersRef.whereEqualTo("name", "Creator");
userNameQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                if (document.exists()) {
                    String userName = document.getString("name");
                    Log.d(TAG, userName + " already exists.");
                } else {
                    Log.d(TAG, userName + " doesn't exist.");
                }
            }
        } else {
            Log.d("TAG", "Error getting documents: ", task.getException().getMessage());
        }
    }
});

Since your screenshot shows that the "Creator" is already taken, the result in the logcat will be:

Creator already exists.
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193