onDataChange stuck in infinite loop

I am trying to create a rating system for restaurants and bars using Firebase. So far I am able to read and write individual ratings. The problem I am having is that in order to calculate the average rating for a particular restaurant I need to get the amount of ratings stored and total value of all ratings stored. At the moment I am struggling to store the amount of ratings. Here is my code

Query RetrieveRating =  databaseReference.child("ratings").child("porterhouse");
RetrieveRating.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot postSnapshot) {

   //get data from snapshot
    String  data = postSnapshot.child("numRating").getValue().toString();

    if (!data.equals(null)) {
        String numRating = (String) postSnapshot.child("numRating").getValue();

        count = Integer.valueOf(numRating);
        count++;

        ratingCounter = Integer.toString(count);

        databaseReference.child("ratings").child("porterhouse").child("numRating").setValue(ratingCounter);
     }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

What is happening is it is taking the current stored value, adding 1 to it and writing it back to the database, however as each time it is stored the onDataChange() method is called, adding plus 1 again and again making an infinite loop. My question is, is there any changes I can make in order to prevent this, or even a different way to configure this? Thanks

UPDATE

json code is as follows:

    {
      "ratings" : {
        "porterhouse" : {
          "numRating" : "0",
          "totalRating" : "0"
        }
  }

Use addListenerForSingleValueEvent

RetrieveRating.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot postSnapshot) {

            //get data from snapshot
            String  data = postSnapshot.child("numRating").getValue().toString();

            if (!data.equals(null)) {
                String numRating = (String) postSnapshot.child("numRating").getValue();

                count = Integer.valueOf(numRating);
                count++;

                ratingCounter = Integer.toString(count);



                databaseReference.child("ratings").child("porterhouse").child("numRating").setValue(ratingCounter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Also you should use firebase transactions for incrementing counters

onDataChange stuck in infinite loop, Sometimes when we run firebase deploy , functions get stuck in a loop and never finish deploying. This seems to happen more often when a new  If your Windows 10 computer is stuck in a continuous endless reboot loop problem after an Upgrade, a Windows Update or Reset or a Blue Screen, then this post gives you some ideas on how to deal

While Martin's answer solves the infinite loop, it leaves a problem in your approach. If two users rate the restaurant at almost the same time, their changes may interfere with each other.

To solve this problem, as Martin says, you should use a transaction:

DatabaseReference ratingRef =  databaseReference.child("ratings/porterhouse/numRating");
postRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        int count;
        try {
            count = Integer.parseInt(mutableData.getValue(String.class));
        } catch (NumberFormatException e) {
            count = 0;
        }
        count++;
        mutableData.setValue(Integer.toString(count));
        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean b,
                           DataSnapshot dataSnapshot) {
        Log.d(TAG, "countTransaction:onComplete:" + databaseError);
    }
});

I'm not really sure why you're storing the counter as a string. I'd highly recommend storing it as a number, in which case this code becomes a lot simpler:

DatabaseReference ratingRef =  databaseReference.child("ratings/porterhouse/numRating");
postRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Integer count = Integer.parseInt(mutableData.getValue(Integer.class));
        if (count == null) count = 0;
        count++;
        mutableData.setValue(count);
        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean b,
                           DataSnapshot dataSnapshot) {
        Log.d(TAG, "countTransaction:onComplete:" + databaseError);
    }
});

Deploy Functions Sometimes Stuck in Infinite Loop · Issue #1674 , I have several problems with this code;. First, if I run it then I chose PUSH and typed two names like "Emily Glassberg" it goes into infinite loop but if I typed only​  Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

if anyone still struggling with it even after adding the addListenerForSingleValueEvent() and you have a hash need to increment value inside the dataChange() which is bad practice as cleared above you simply can add a boolean object initially false and test inside the dataChange() method if it still false => setvalue and set the boolean to true ,it translate for the case above as :

boolean is_added = false;

onDataChange(){
//after increment and befor setValue()
if(!is_added){
//setValue() set what ever you want on that reference 
is_added = true ;
}
}

C++ code crashes and has an infinite loop, I found some newsgroup postings from about 4 years ago and back then there was no way to terminate a script from running in a infinite FOR loop without using​  when an loop is running ctrl + c (just ctrl and c ) will exit any loop.. You have to do this in the command window when the loop is running (i.e. you do not have the >> prompt and it shows 'busy' on the status bar-- which is usually the case when MATLAB is performing any operation..

android - onDataChange uvízl v nekonečné smyčce, onDataChange stuck in infinite loop · android studio can not show all the packages in a jar file · TabLayout setIcon with a certain size · accessing iis express from  What is happening is it is taking the current stored value, adding 1 to it and writing it back to the database, however as each time it is stored the onDataChange() method is called, adding plus 1 again and again making an infinite loop.

Force matlab to quit while stuck in an infinite loop?, How to Fix Windows 10 Stuck in Infinite Boot: A reboot loop situation occurs when Windows fails to correctly load up after turning on the PC. The computer reaches a certain stage before the logon

android, How To Fix iPhone Stuck In Boot Loop On Apple Logo. How to fix an iPhone that is stuck in a bootloop on the logo in an endless reboot cycle. This guide will show you how to fix an iPhone that

Comments
  • Post your json structure
  • @MartinDeSimone updated to show relavent part of json code
  • That would really make a loop based on your code because the ChildEventListener would listen to all changes on that specific path and changing that path inside the listener would trigger it again and again
  • Could you post your whole JSON Database Schema?
  • Thank you Martin, working perfectly. Really appreciate your help