Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

android - Changing value in Firebase results in infinite loop

I want to implement a function of 'add to favorite' by clicking in a star (button). When i click for the first time, set a value to user favorite in firebase and the star will be yellow, and when i click again, it removes from list, and star back to normal. I'm tryin' this code, but is looping. How can i solve this?

    final DatabaseReference ref = FirebaseDatabase.getInstance().getReference( "Usuarios" );
    ref.child( mAuth.getUid() ).child( "Favoritos" )
            .addValueEventListener( new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if (dataSnapshot.exists()) {
                        botaoFavorito.setImageResource(  R.drawable.ic_favoritos  );
                        ref.child( mAuth.getUid() ).child( "Favoritos" ).child( posicao ).setValue(null);
         
                    }
              else {
                        botaoFavorito.setImageResource(  R.drawable.ic_favorito_adicionado  );
                        ref.child( mAuth.getUid() ).child( "Favoritos" ).child( posicao ).setValue(posicao);
                       
                    }
                }

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

                }
            } );
question from:https://stackoverflow.com/questions/65844809/recycler-view-creates-infinity-posts-when-i-tap-the-like-button

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use addListenerForSingleValueEvent instead of addValueEventListener.

  • addValueEventListener - which goes on listing events continuously.
  • addListenerForSingleValueEvent- listens for the very first event only.

In your code, just replaceaddValueEventListener with addListenerForSingleValueEvent, that's all, leave the reamaining portion of the code intact.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...