Count the number of records in firebase

Asked

Viewed 1,192 times

2

Good morning Developers! I’m having a hard time in a project that I can’t move forward, here’s the problem/scenario: We have a screen that brings information, a message, and on the screen there is the button to bookmark that message, this information is saved in the Firebase Realtimedatabase, in this scenario I need the following elements: when the user clicks on imLike save as liked or neglected depending on the current situation(is working), every time check if that message had been liked by that user before(as the messages are generated on the screen randomly this check if the user had liked before should be done with the same frequency - is working already), and last but not least a Textview show how many likes that message already has (this I still could not do).

The function below is called as soon as Activity is startada and brings the following results: if the current user has already given like in that message the favorite image receives the red coloring and Textview tbm.

private void verificarCurtida(String versiculo, String usuario) {
    String cripto = CriptografiaBase64.criptografarVersiculo(versiculo);

    likeRef = ConfiguracaoFirebase.getFirebaseReference()
            .child("VERSICULOS")
            .child(cripto)
            .child("LIKES")
            .child(usuario);

    //Verificando se esse versiculo já foi curtido antes
    likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pesquisando o idUsuarioe as curtidas
            if (dataSnapshot.getValue() != null){
                //Se retornar valor quer dizer que já fi curtida antes por esse usuário
                imLike.setImageResource(R.drawable.ic_favorite);
                tvLikes.setTextColor(Color.parseColor("#FF1E1E"));
            } else {
                imLike.setImageResource(R.drawable.ic_favorite_border);
                tvLikes.setTextColor(Color.parseColor("#000000"));
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

below is the same method, but with the attempt of adding the user count in the knot:

private void verificarCurtida2(String versiculo, String usuario) {
    String cripto = CriptografiaBase64.criptografarVersiculo(versiculo);
    final int contar = 0;

    likeRef = ConfiguracaoFirebase.getFirebaseReference()
            .child("VERSICULOS")
            .child(cripto)
            .child("LIKES");
    //.child(usuario);

    //Verificando se esse versiculo já foi curtido antes
    likeRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pesquisando o idUsuarioe as curtidas
            if (dataSnapshot.getValue() != null){
                for (DataSnapshot data: dataSnapshot.getChildren()){

                    if (data.getValue().equals(preferencias.getCHAVE_ID())){
                        //Se retornar valor quer dizer que já fi curtida antes por esse usuário
                        imLike.setImageResource(R.drawable.ic_favorite);
                        tvLikes.setTextColor(Color.parseColor("#FF1E1E"));
                        contar++;

                    } else {
                        imLike.setImageResource(R.drawable.ic_favorite_border);
                        tvLikes.setTextColor(Color.parseColor("#000000"));
                        contar++;
                    }

                }
                //tvLikes.setText((int) dataSnapshot.getChildrenCount());

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    tvLikes.setText(contar);

}

Below, follows the structure in firebase, where I have the following nodes: VERSICULOS > IDVERSICULO > LIKES > ID’s of the users who clicked on like; inserir a descrição da imagem aqui

as image I need the following result: VERSICULOS > IDVERSICULO > LIKES > 3 (Textview gets 3).

  • 1

    //tvLikes.setText((int) dataSnapshot.getChildrenCount()) what happens here?

1 answer

2

Okay. Your reference points to ("Likes"), which has 3 Childs, correct?

Do it...

Point your reference to a node behind, if it is the first let empty ...db.getReference();

from there on down...

referencia.addValeEventListener(new ValueEventListener()
{
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

         Likes likes = dataSnapshot.getvalue(Likes.class);
         //o numero de nó da referencia vai ser o tamanho do arrayList retornado
         int nChilds = likes.likes.size();
}
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
};

The Likes class would look like this...

Class Likes{
     //o nome do arraylist deve ser o mesmo do nó pai******
     publlic ArrayList<String> likes;
}

Browser other questions tagged

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