Search code examples
androidfirebasefirebase-realtime-databasegeofire

how can i count the available user in specific loaction radius with geofire query?


right now m using dataSnapshot.getChildrenCount but it only counts the node available in a child.

here is my code

 GeoFire geoFire = new GeoFire(ref.child("Userlocation"));
    GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latitude, longitude), Raius);

    geoQuery.addGeoQueryDataEventListener(new GeoQueryDataEventListener() {
        @Override
        public void onDataEntered(DataSnapshot dataSnapshot, GeoLocation location) {


            int userCounter = (int) dataSnapshot.getChildrenCount();
            ads5_userCounter.setText(userCounter + "");


        }

        @Override
        public void onDataExited(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onDataMoved(DataSnapshot dataSnapshot, GeoLocation location) {

        }

        @Override
        public void onDataChanged(DataSnapshot dataSnapshot, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {

        }

        @Override
        public void onGeoQueryError(DatabaseError error) {

        }
    });

this method is not counting all the user avilable at this location radius. please help.


Solution

  • The onDataEntered method is called for each node that is within the range. Once onDataEntered has been called for all nodes that are initially in range, the onGeoQueryReady method is called. That means that you can increment a counter in onDataEntered and then show it in onGeoQueryReady.

    long count = 0;
    geoQuery.addGeoQueryDataEventListener(new GeoQueryDataEventListener() {
      @Override
      public void onDataEntered(DataSnapshot dataSnapshot, GeoLocation location) {
        count++;
      }
      @Override
      public void onDataExited(DataSnapshot dataSnapshot) { }
      @Override
      public void onDataMoved(DataSnapshot dataSnapshot, GeoLocation location) { }
      @Override
      public void onDataChanged(DataSnapshot dataSnapshot, GeoLocation location) { }
    
      @Override
      public void onGeoQueryReady() {
        ads5_userCounter.setText(""+count);
      }
    
      @Override
      public void onGeoQueryError(DatabaseError error) {
        throw databaseError.toException(); // don't ignore errors
      }
    });