Check if a value exists in the Firebase Realtime Database

Asked

Viewed 1,117 times

2

I have a database with this structure:

árvore de dados do banco

what happens is that when creating a new user, I need to check if there is no longer a registered equal nickname, but I am not able to do this. Here’s the code that’s going wrong, with some comments on what I think should be right:

if (edtCadSenha.getText().toString().equals(edtCadConfirmaSenha.getText().toString())) {
                referencia = ConfiguracaoFirebase.getFirebase();
                //nessa linha, é definida a ordem de busca. no laço usuarios procurando por
                //resultados onde o nick digitado pelo usuário seja igual a algum já cadastrado
                //e, adicionando .limitToFirst(1), limita o número de resultados necessários
                //para terminar a execução a um só.
                Query buscaNick = referencia.child("usuarios").orderByChild("nickname").equalTo(edtCadNickname.getText().toString()).limitToFirst(1);
                buscaNick.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        //se cair aqui, significa que encontrou um nick igual

                        Toast.makeText(CadastroActivity.this, "Esse nick já existe, escolha outro por favor!", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        //se caiu aqui, significa que não tem um nick igual no bd, então
                        //o usuário pode seguir o cadastro normalmente.
                        usuarios = new Usuarios();
                        //recupera todos os valores nos campos preenchidos na tela pelo usuário
                        //e armazena no objeto de usuário
                        usuarios.setNome(edtCadNome.getText().toString());
                        usuarios.setNickname(edtCadNickname.getText().toString());
                        usuarios.setEmail(edtCadEmail.getText().toString());
                        usuarios.setSenha(edtCadSenha.getText().toString());
                        usuarios.setAniversario(edtCadAniversario.getText().toString());
                        //faz a checagem de qual botão de radio está selecionado para preencher o campo sexo
                        if (rbFeminino.isChecked()) {
                            usuarios.setSexo("Feminino");
                            cadastrarUsuario();
                        } else if(rbMasculino.isChecked()) {
                            usuarios.setSexo("Masculino");
                            cadastrarUsuario();
                        }

In the example, the query only falls in the first example, and shows the message "This nick already exists"

2 answers

1

Beauty gurized? It follows as "make the comparison", in this case I tried to search for an existing email within my user table. For this, I made a query organized by email that compares what I passed in Materialedittext (can be any string) with the result of the query made. Behold:

public void validateEmail(){
    Query buscaEmail = FirebaseDatabase.getInstance().getReference("User")
            .orderByChild("email")
            .equalTo(metEmail.getText().toString());

    buscaEmail.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            /* Getting users if exists using the email provided as key*/
            if(!snapshot.exists()) {
                makeSignUp();
            }else{
                Toast.makeText(signUp.this, "Este email ja esta cadastrado.", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(signUp.this, "Algum erro ocorreu!", Toast.LENGTH_SHORT).show();
        }
    });
}

In the case in the creation of the query getReference("User") sorted by email and then compared to the text of Materialedittext I used. Soon after I did the Eventlistener, I think that part I should already know, so I just go to the important: In the query, if there is a snapshot, it means that there was a return of your query, so soon after I just checked if there was a snapshot with if(!snapshot.exists()) in my case could not exist to continue to register. I hope I’ve helped.

"Update without Where is an obligation of the intern" - The Trainee.

-1

@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) { 

          If(dataSnapshot.exists()){
                    //se cair aqui, significa que encontrou um nick igual

                    Toast.makeText(CadastroActivity.this, "Esse nick já 
                         existe, escolha outro por favor!", 
                 Toast.LENGTH_LONG).show();

              }else{
                      Continue...........
               }
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.