androidfirebaseauthenticationfirebase-realtime-database

check if a key belongs to one or another children in firebase


I have a login and inside the login I need to check if the user belong to "Administrador" or "Chofer" (children of firbase database tree) in order know which screen I´m going to open, I have the following code:

mAuth.signInWithEmailAndPassword(usuario, pass)
    .addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            if (!task.isSuccessful()) {

                Toast.makeText(Login.this, "Los Datos administrados no son correctos",
                        Toast.LENGTH_SHORT).show();
                mProgress.dismiss();
            } else{
                Toast.makeText(Login.this, "Bienvenido... ",
                        Toast.LENGTH_SHORT).show();
                //loadAdmin(task.getResult().getUser());
                 mProgress.dismiss();
                if(AdminFirebase.esAdmin(task.getResult().getUser())){
                    AdminFirebase.loadAdmin(task.getResult().getUser());
                    Intent intento=new Intent(Login.this, Principal.class);
                    intento.putExtra("Usuario", "administrador");
                    startActivity(intento);
                }
                else{
                    ChoferFirebase.loadChofer(task.getResult().getUser());
                    Intent intento=new Intent(Login.this, Principal.class);
                    intento.putExtra("Usuario", "chofer");
                    startActivity(intento);
                }

            }
        }
    });

and the method I have problems with its the following one:

  public boolean esAdmin(FirebaseUser user){

DatabaseReference adminRef= ref.child("Administradores");
        if(adminRef.child(user.getUid()).getKey() == null) {
           return false;
        } else {
            return true;
        }
    }

and here its the JSON structure from firebase:

  "Administradores" : {
    "2XPtAqaBDHXm8R5rLWjJ2pIzADi1" : {
      "chapas" : "bbb222,idTaxi",
      "email" : "gastondelacruz@gmail.com",
      "nombre" : "gaston",
      "telefono" : "122323232"
    }
  },
  "Choferes" : {
    "6YWaOqBDDlOmrcpgm84dm5WipmH3" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F86?alt=media&token=4d9bbf4b-f884-459a-820a-ee1027668f1c",
      "nombre" : "ccccc",
      "taxi" : "aaa111"
    },
    "6lvl464H3IYfFJOBoE9tzl4IzVu1" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F35?alt=media&token=1bdb1d06-e4a5-41e7-a5ae-9f8a77d1f515",
      "nombre" : "facuputito"
    },
    "7gOzX9azHSQLP9Enji0wZMVKYzz1" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F32?alt=media&token=7d6013a6-4063-4b1f-9171-209ede2562d6",
      "nombre" : "test2"
    },
    "8iE2DPGY0OWh4sbRTyCtWaDyUct1" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F86?alt=media&token=f28567aa-5514-48f4-957d-b413f14867ee",
      "nombre" : "bbbbb"
    },
    "BT1C40DMHRac7LRHuaQQmfeFe7H3" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F35?alt=media&token=5b160731-221a-44e2-9362-e5b4edf9dde9",
      "nombre" : "name"
    },
    "LpD2brAzIPTwpP5BFLd0ie8lAX92" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F86?alt=media&token=1681459e-f25b-4ea3-9599-756cf6617a46",
      "nombre" : "kakaka"
    },
    "MTYu8GWex8Ox3hXEPhjTwFlmx463" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F86?alt=media&token=2a0075c1-8e4a-4a21-9ea4-b3f03123989c",
      "nombre" : "aaaaa"
    },
    "Ndtq2knyyMMs9AlU1ACTiSm4twE3" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F35?alt=media&token=c67af765-d9b3-4262-b047-01f1ec353dc6",
      "nombre" : "facutragasable"
    },
    "jdzkv8PrHmYUuRU1lCgoGZgTeQ12" : {
      "imagen" : "https://firebasestorage.googleapis.com/v0/b/taxiexpress-192df.appspot.com/o/fotos%2F35?alt=media&token=c67af765-d9b3-4262-b047-01f1ec353dc6",
      "nombre" : "facu"
    }
  }

Solution

  • Try this:

    // make this variables can be accessed for whole class
    int isAdmin = -1;
    int isChofer = -1;
    
    ...
    
    // then you need to check if user uid is in "Administradores" or "Choferes"
    
    // check inside "Administradores"
    DatabaseReference adminRef= ref.child("Administradores");
    adminRef.child(user.getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            isAdmin = dataSnapshot.exists() ? 1 : 0;
            validateUser();
        }
        ...
    });
    
    // check inside "Choferes"
    DatabaseReference choferRef= ref.child("Choferes");
    choferRef.child(user.getUid()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            isChofer = dataSnapshot.exists() ? 1 : 0;
            validateUser();
        }
        ...
    });
    
    ...
    
    // then validate each time one of those two event listener get value,
    // you validate is it exist in "Administradores" or in "Choferes"
    
    private void validateUser() {
        if (isAdmin > 0 && isAdmin == 1) {
            // user is admin
        } else if (isChofer > 0 && isChofer == 1) {
            // user is chofer
        }
    
        // if both method above is false then it means
        // one or all of value event listener have not finished
    }
    

    I've added comments inside the code sample, hope that help to understand how it works. It actually is a simple method if you've read Firebase Guide on Read and Write Data on Android