Kizzle
Kizzle

Reputation: 101

How to stop Firebase database infinite looping

I am creating an app and part of it's features in user interaction. I want to store user comments on a post and I do not want to limit the amount of comments any one user can make. I do this by assigning a random number as the .setValue of the database entry.

With this implementation, whenever the comment is sent to the database it is stuck in an infinite loop where it will continually update with the same string entered in the text box but it will constantly generate new posts. Full code;

        sendComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            commitPost();
            finish();
        }
    });

}

private void commitPost() {
    commentProgress.setMessage("Posting");
    commentProgress.show();
    final String commentInput = commentText.getText().toString().trim();

    if(TextUtils.isEmpty(commentInput)){
        Snackbar.make(commentLayout,"You haven't finished your post yet",Snackbar.LENGTH_SHORT);
    }else{

        commentDB.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String uniqueId = UUID.randomUUID().toString();
                commentDB.child(postID).child("Comments").child(uniqueId).setValue(commentInput);
                commentProgress.dismiss();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

The problem lies in the commentDB.addValueEventListener

Upvotes: 1

Views: 1485

Answers (1)

Juan Cruz Soler
Juan Cruz Soler

Reputation: 8254

The problem is that you set a listener for data changes and you also change data inside it (so it is called).

You don't need the listener, just add:

else {
    String uniqueId = UUID.randomUUID().toString();
    commentDB.child(postID)
             .child("Comments")
             .child(uniqueId)
             .setValue(commentInput); 
    commentProgress.dismiss();
}

Upvotes: 5

Related Questions