Firebase reference with child variable

0

I reformulate the question. Could it be done in some way to count the votes with this database?

I think I would need to put the child right to pick up all the users' uid

mDatabase = FirebaseDatabase.getInstance().getReference().child( "Events" ).child( code ).child( mAuth.getCurrentUser().getUid() );
    mDatabase.addValueEventListener( new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            Event event = dataSnapshot.getValue( Event.class );

            List<String> usuarios = new ArrayList<>();

            for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){

                usuarios.add(childSnapshot.child("vote").getValue(String.class));

                Log.e("nombre ", usuarios+" estos son los usuarios OK");
                }
    
asked by lujan 15.07.2018 в 16:20
source

1 answer

0

I have a structure to count the amount of likes of certain posts of my users. To make it easier, outside the Users node you have create another that is called Votes, inside of Vows you save the UID of the user and below the votes with push (), with the value true, so, then the only thing you do is to enter that node Votes and with getChildrenCount(); depending on the user you can count the number of votes he has

Here I leave an example of my structure to tell how many likes that photo has, I explain it as you should have it even if mine is different

Here, instead of Likes, you will have Votes, this is a node separated from Users, not inside Users

Now, the only thing you have left is to access that node with the UID of the user and get the children to know the amount, this way you would not need a for if you want to know the number of votes of each user

public void countVote(){
    mDatabase = FirebaseDatabase.getInstance().getReference().child( "Events" ).child( code ).child("Users").child("Votos").child(userID);
    mDatabase.addValueEventListener( new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            long cantVotos  = dataSnapshot.getChildrenCount();

            }
        }

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

        }
    } );

}

to add the user's vote to Votes the only thing you do is this

First I would separate the reference so as not to have it declared all together

mDatabase = FirebaseDatabase.getInstance().getReference().child("Votos");

and then I put the value of the user when he votes

mDatabase.child(userID).push().setValue(true);

PS: if you do not want to use the user's uid, you can use the same email that you use in Users

    
answered by 15.07.2018 / 18:55
source